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;
cast() method casts an object to the class or interface represented by this Class object.
For example: Type intType = typeof(Int32); object value1 = 1000.1; // Variable value2 is now an int with a value of 1000, the compiler // knows the exact type, it is safe to use and you will have autocomplete int value2 = Convert.
Type casting in TypeScript can be done with the 'as' keyword or the '<>' operator.
In TypeScript, you can use the as keyword or <> operator for type castings.
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.
Casting generally is a compile-time concept, i.e. you have to know the type at compile-time.
Type Conversion is a runtime concept.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With