30

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;
9
  • Have you looked into generics? MyClass<T>, and then var newObject = givenObject as T. Jan 25, 2012 at 15:48
  • I've used generics for the common objects. But there are special ones which need to be casted explicitly - besides the generic ones. Jan 25, 2012 at 15:57
  • What you mean by special objects?
    – H27studio
    Jan 25, 2012 at 16:18
  • Objects was probably the wrong word. We've got lots of custom DataFields (string, int, DateTime, ...). But there are also some we couldn't handle with generics, because there handling wasn't relative enought to the handling of integers and strings. Jan 25, 2012 at 16:27
  • What is the intent? Do you want to treat the given object as a MyClass? If so, why not just var newObject = givenObject as MyClass. If not, then what is the type of newObject? How are you going to access its members? What am I missing? if you know the type at compile time then you should be able to cast as that type. If you do not know the type at compile time, how are you planning to access the object?
    – AlanT
    Jan 25, 2012 at 16:34

5 Answers 5

10

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();
12
  • 17
    I think the OP wants some kind of dynamic casting at runtime.
    – ken2k
    Jan 25, 2012 at 15:41
  • 1
    Then that is a different problem. Also to cast to do what? Casting is a compile time concept.
    – Aliostad
    Jan 25, 2012 at 15:44
  • "newObjectType is an instance of the type not the type itself" When you say "the type", are you referring to MyClass? Because that's not true at all.
    – sepp2k
    Jan 25, 2012 at 15:45
  • Oh, I overlooked that type-safety thing I've heard of in .NET :-D I've tried givenField = givenField as NewType and I wondered that this givenField still lacks of a field which is just given in NewType, afterwards. But your answer gave me the clue. Sorry.^^ Jan 25, 2012 at 15:46
  • 3
    This answer needs to be edited or deleted. Showing how to call MethodInfo.Invoke still doesn't answer the question.
    – makhdumi
    Jan 30, 2017 at 5:42
9

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.

6

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.

0
5

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);
2
  • 3
    Except newObjectType must implement the IConvertible interface. Otherwise, it throws System.InvalidCastException.
    – Suncat2000
    Jan 10, 2020 at 20:46
  • 3
    Since this returns object it will then be unable to be used as an input to some method.. which returns us back to the how to dynamically cast problem. Mar 5, 2020 at 19:51
2

Maybe you can solve this using generics.

public void CastToMyType<T>(object givenObject) where T : class
{
   var newObject = givenObject as T;
}
3
  • Nope:The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
    – tobewan
    Feb 20, 2012 at 22:10
  • public void CastToMyType<T>(object givenObject) where T : class { var newObject = givenObject as T; } Feb 21, 2012 at 13:14
  • With this you still have the same problem when you want to call CastToMyType() with a type retrieved at runtime. You are essentially trying to do this: CastToMyType<someVar.GetType()>() which is not possible. May 15, 2014 at 15:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.