Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast with GetType()

People also ask

How do I use GetType?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

What is GetType?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.

What is return type of GetType ()?

The gettype() function returns the type of a variable.


I can't think of why you'd want to cast as GetType(), because you wouldn't be able to do anything to useful with the result, without knowing the type at compile time anyway.

Perhaps what you are looking for, is being able to Convert. If that is the case, the following should work for you:

object input = GetSomeInput();
object result = Convert.ChangeType(input, someOtherObject.GetType());

We use this when reading values from the registry which are all stored as strings, and then stuffing them into properties using reflection.


Your intent is very unclear; however, one option is generics and MakeGenericMethod in particular. What do you want to do with this? For example:

static class Program
{
    static void Main()
    {
        object obj = 123.45;
        typeof(Program).GetMethod("DoSomething")
            .MakeGenericMethod(obj.GetType())
            .Invoke(null, new object[] { obj });
    }
    public static void DoSomething<T>(T value)
    {
        T item = value; // well... now what?
    }    
}

So now we have the value, typed as double via generics - but there still isn't much we can do with it except for calling other generic methods... what was it you want to do here?


You can use the Activator.CreateInstance method to create an instance from a type.

FYI reflection is SLOOWWWW, so if you need to do this cast many times in a row, it may be better to define your types in an enum or something like this then create instances without using reflection.