Michael Schnerring
Michael Schnerring

Reputation: 3661

cast object with a Type variable

The following doesn't work, of course. Is there a possible way, which is pretty similar like this?

Type newObjectType = typeof(MyClass);

var newObject = givenObject as newObjectType;

Upvotes: 30

Views: 54465

Answers (5)

Sebastian Badea
Sebastian Badea

Reputation: 89

You can use Convert.ChangeType. According to msdn, it

returns an object of a specified type whose value is equivalent to a specified object.

You could try the code below:

Type newObjectType = typeof(MyClass);

var newObject = Convert.ChangeType(givenObject, newObjectType);

Upvotes: 5

Aliostad
Aliostad

Reputation: 81660

newObjectType is an instance of the Type class (containing metadata about the type) not the type itself.

This should work

var newObject = givenObject as MyClass;

OR

var newObject = (MyClass) givenObject;

Casting to an instance of a type really does not make sense since compile time has to know what the variable type should be while instance of a type is a runtime concept.

The only way var can work is that the type of the variable is known at compile-time.


UPDATE

Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.

Type Conversion is a runtime concept.


UPDATE 2

If you need to make a call using a variable of the type and you do not know the type at compile time, you can use reflection: use Invoke method of the MethodInfo on the type instance.

object myString = "Ali";
Type type = myString.GetType();
MethodInfo methodInfo = type.GetMethods().Where(m=>m.Name == "ToUpper").First();
object invoked = methodInfo.Invoke(myString, null);
Console.WriteLine(invoked);
Console.ReadLine();

Upvotes: 10

Silas
Silas

Reputation: 1150

I recently had the case, that I needed to generate some code like in Tomislav's answer. Unfortunately during generation time the type T was unknown. However, a variable containing an instance of that type was known. A solution dirty hack/ workaround for that problem would be:

public void CastToMyType<T>(T hackToInferNeededType, object givenObject) where T : class
{
   var newObject = givenObject as T;
}

Then this can be called by CastToMyType(instanceOfNeededType, givenObject) and let the compiler infer T.

Upvotes: 6

Tomislav Markovski
Tomislav Markovski

Reputation: 12346

Maybe you can solve this using generics.

public void CastToMyType<T>(object givenObject) where T : class
{
   var newObject = givenObject as T;
}

Upvotes: 2

StuartLC
StuartLC

Reputation: 107237

You can check if the type is present with IsAssignableFrom

if(givenObject.GetType().IsAssignableFrom(newObjectType))

But you can't use var here because type isn't known at compile time.

Upvotes: 9

Related Questions