0

I want to create an instance of type t with reflection, that is


Type t = typeof(string);
string s = (t)Activator.CreateInstance(t); // this fails because of convertion
string s = Activator.CreateInstance(t) as t // also fails

Is there a way to perform such a convertion? Thanks.

1
  • 1
    Why would you want to do this? If you know the compile-time type of the variable then why not construct the object normally? Commented Jan 6, 2010 at 15:24

2 Answers 2

4

Yes. You have to convert to string, not to t. You may want a generic method, alternatively:

public T GetInstance<T>()
{
    Type t = typeof(T);
    T s = (T)Activator.CreateIstance(t);
    return s;
}

As things stand you are attempting to cast an object that is actually an instance of System.String to type System.Type...

Sign up to request clarification or add additional context in comments.

3 Comments

You could just add a where T : new() contstraint on the method and the body would then be a single line: return new T();
Very true, and would be safer as types not implementing a paramaterless constructor could be picked up at compile time.
If I recall correctly there is a generic overload as well, so you should be able to do Activator.CreateInstance<T>();
1

Try this:

string s = (string)Activator.CreateInstance(t);

Activator.CreateInstance returns an instance boxed in an object so it must be cast to the correct type before you can use it.

In your example t is a Type object variable and not a type reference. You must either specify the type directly as in my example or you can use generics.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.