How to create extension methods for Types

Viewed 12719

I am writing an extension method for parsing JSON string for any given type. I wanted to use the method on types instead of instances like many examples we already know, but I somewhat feel it is not supported by Visual Studio. Can someone enlighten me here? The following is the method:

public static T ParseJson<T>(this T t, string str) where T: Type
{
    if (string.IsNullOrEmpty(str)) return null;
    var serializer = new JavaScriptSerializer();
    var obj = serializer.Deserialize<T>(str);
    return obj;
}

I want to call the method in this fashion:

var instance = MyClass.ParseJson(text);

Thanks

5 Answers

As stated in the accepted answer, you can't. However, provided that you have an extension method that can be called from an instance of T:

public static T ParseJson<T>(this T t, string s)

You could write a utility method like this:

public static T ParseJson<T>(string s)
    where T: new()
    => new(T).ParseJson(s);

And call it like this:

var t = Utilities.ParseJson<T>(s);

I am afraid that's the best you can do...

You can create and extension method

public static class MyExtensions
{
    public static string Serialize<T>(this T self)
    {
        return JsonSerializer.Serialize(self);
    }
}

And use it like

instance.Serialize();

You don't have to use it like instance.Serialize<Type>(); because most of the time (if not all the time) it can be inferred from the usage.

Related