Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as a Type?

Tags:

c#

I have an object that is passed to me as ISomething. I need to serialize the object however my serilizer expects a type parameter of a concrete type i.e:

string xml = Utilities.Serialize<ConcreteType>(myObject);

Basically I want to to the same thing as this guy: Creating a generic object based on a Type variable

however I dont want to create a new instance of an object I want to use the resulting type as a parameter to my generic class.

So my question in a nutshell is how do I create some variable that represents the concrete type of some object that I can use with a generic class like this:

string xml = Utilities.Serialize<ConcreteType>(myObject);

where ConcreteType is what I need to create.

like image 856
Sam Avatar asked Dec 13 '25 19:12

Sam


1 Answers

So let's say you've got something like:

public static class Util
{
    public static T Foo<T>(object obj)
    {
         // Do actual stuff here
         return default(T);
    }
}

Normally, the compiler would wire up any usage of this method, swapping in the appropriate generic variant based on what you passed it. We no longer can rely on the compiler if you have a variable containing the Type - but we can ask the class to give us the variant we want:

public void DoFooWith(object blob)
{
    // Get the containing class
    var utilType = typeof(Util);
    // Get the method we want to invoke
    var baseMethod = utilType.GetMethod("Foo", new Type[]{typeof(object)});
    // Get a "type-specific" variant
    var typedForBlob = baseMethod.MakeGenericMethod(blob.GetType());
    // And invoke it
    var res = typedForBlob.Invoke(null, new[]{blob});
}
like image 149
JerKimball Avatar answered Dec 15 '25 08:12

JerKimball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!