dob_xml

Is it possible to do the following

private static void Main(object toCast)

{

Type toCastTo = GetCustomType();

//now I would like to be able to cast the object toCast to be an instance of MyCustomClass

//assume MyCustomClass could be any class and the only way this function knows about it is

//via GetCustomType()

}

private Type GetCustomType()

{

return typeof(MyCustomClass);

}



Re: Visual C# Language Cast to instance of type

Peter Ritchie

typeof only creates an instance of Type, which is documented as only being able cast to to Object, MemberInfo, _Type and IReflect. You have to create an instance of your type or a subclass of that type in order to cast to that type






Re: Visual C# Language Cast to instance of type

dob_xml

So, how do I create an instance of a type when all I have is the Type information

However I have solved my original problem.....

PropertyInfo pi = toCast.GetType().GetProperty("Age");

and

pi.GetValue(toCast, null).ToString()

My problem was I did not think

toCast.GetType().GetProperty("Age");

would work while toCast was an object, I thought I needed to cast it to MyCustomClass before I could access the properties

Thanks for the reply.





Re: Visual C# Language Cast to instance of type

Peter Ritchie

There's a couple of ways to instantiate a type based on just a Type object. One:

Code Snippet
Type type = typeof(BaseClass);
Object o = Activator.CreateInstance(type);

Another:

Code Snippet

Type type = typeof(BaseClass);
ConstructorInfo ci = type.GetConstructor(new Type[]{});
o = ci.Invoke(null);