views:

98

answers:

3

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

+2  A: 

The short answer is it cannot be done; extension methods need to work on an instance of something.

David Hedlund
+1  A: 

You can't create extension methods that apply to the type itself. They can only be called on instances of a type.

LukeH
and null instances of that type which is one of the redeeming values of ext. methods :) string val = null; val.IsNullOrEmpty()Sweet...
Brian Rudolph
+3  A: 

To use the extension method, you would have to do:

var instance = typeof(MyClass).ParseJson(text);

The token "MyClass" is not a Type instamce intself, but using typeof will get you a Type to operate on. But how is this any better than:

var instance = JsonUtility.ParseJson<MyClass>(text);

Edit: Actually, the code for the extension method still would not do what you wanted. It will always return a "Type" object, not an instance of that Type.

Chris
Your edit is correct Chris. This did not work for me.
Randy Eppinger