3

I have function as below .

public static object getClassInstance(string key, object constructorParameter)
{
         // body here
}

Key variable will have my class name . I need to return the new instance of the class . If the constructorParm is null then i need to load the class with default constructor else with the constructor parameter passed. How do i do this ?

ADD :

I wrote the code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Catalyst.BO.StudentProfileBO;
using Catalyst.BO.ReportBO;
using Catalyst.DAL.ReportDAO;
using System.Collections;
using System.Data;

namespace Catalyst.BO.Factory
{
    public class CFactory
    {
        public static object getClassInstance(string key, params  object[] constructorArgs)
        {
            string assemblyPath = null;
            string customClassName = key.Substring(0, 1) + "Custom" + key.Substring(1);

            DataSet objDataset = getAssemblyInfo(key);
            if (objDataset != null && objDataset.Tables.Count > 0 && objDataset.Tables[0].Rows.Count > 0)
            {
                assemblyPath = objDataset.Tables[0].Rows[0]["ACA_ASSEMBLY_PATH"].ToString();
            }

            Assembly assembly;
            Type type;

            if (assemblyPath != null && assemblyPath != string.Empty)
            {
                assembly = Assembly.LoadFile(assemblyPath);
                type = assembly.GetType(customClassName);
            }
            else // if no customisation
            {
                type = Type.GetType(key);
            }

            object classInstance = constructorArgs == null ? Activator.CreateInstance(type) : Activator.CreateInstance(type, constructorArgs);
            if (classInstance == null) throw new Exception("broke");
            return classInstance;
        }
    }
}

key passed to the function is "CReportBO". CReportBO is accessible in the function's scope . but in //if no customization section (i.e type = Type.GetType(key) ) , type returns me null . whats wrong ?

3
  • 1
    what if you want to use null as the parameter ;p Commented Aug 31, 2011 at 7:04
  • i don have dat condition as of nw . but i ll handle it wen it comes . How do I handle why existing situation ? Commented Aug 31, 2011 at 7:06
  • @Nithesh: Note you can format lines as code by indenting them four spaces. The "{}" button in the editor toolbar does this for you. Others have done it for you on this question, but next time you should try it yourself. Click the orange question mark in the editor toolbar for more information and tips on formatting. Commented Aug 31, 2011 at 13:22

5 Answers 5

7

If key is either assembly-qualified, or namespace-qualified within either the core assemblies or the calling assembly, then:

Type type = Type.GetType(key);
return constructorParameter == null ? Activator.CreateInstance(type)
          : Activator.CreateInstance(type, constructorParameter);

I wonder, though, if:

public static object getClassInstance(string key, params object[] args)

is more flexible, allowing:

Type type = Type.GetType(key);
return Activator.CreateInstance(type, args);

with usage such as:

object o = getClassInstance(key); // uses default constructor
object o = getClassInstance(key, null); // passes null to single parameter
object o = getClassInstance(key, 123, "abc"); // etc
Sign up to request clarification or add additional context in comments.

9 Comments

Yours added the info that you could change consturctorParameter to be a param array to support additional constructors, i think it was worth keeping.
yup, dat was worth keeping , plz add it .
@Marc Gravell♦ can u check the issue which i posted ?
@Nithesh what is the namespace qualified name of CReportBO - is it Some.Whatever.CReportBO, for example? Is it a nested type (in which case the name is actually Namespace.Outer+Nested, not Namespace.Outer.Nested. What assembly is it in? If it isn't the same as the calling code, then you'll need to either use the assembly qualified name, or use an Assembly instance, i.e. typeof(SomeTypeInThatAssembly).Assembly.GetType(key)
its Catalyst.BO.ReportBO . I have imported it through using statement I updated the question with class also . jus have a relook . Class is in same assembly
|
1

You should be able to do something like this:

Activator.CreateInstance(Type.GetType(keyBindings), constructorParameters)

You can change your method signature to be public static object getClassInstance(string key, params object[] constructorParameters) if you want to allow the possibility of multiple constructor arguments.

Comments

0

You will want something similar to this:

    public object CreateMyObject(string name, object constructorParam)
    {
        Type t = Type.GetType(name);
        if (t != null)
        {
            object o = Activator.CreateInstance(t, constructorParam != null ? new[] { constructorParam } : null);
            return o;
        }

        return null;
    }

Of course you will need to add the appropriate error handling.

Damn, beaten to it by Marc, his answer takes precedence over mine :)

Comments

0

You can achieve the similar function using C# Activator.CreateInstance method.

Have a look at this MSDN document http://msdn.microsoft.com/en-us/library/dd384354.aspx

You could do lot more using Activator class.

Cheers, B

Comments

0

First, you should get type from your string:

Type t = testAssembly.GetType(key);

Then create an instance of your type:

Object o = Activator.CreateInstance(t, constructorParameter);

And o is an object of your type

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.