24

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Codism
  • 5,928
  • 6
  • 28
  • 29
  • Note that `ParseJson` returns a `Type` not a `MyClass` with this definition. – dtb Dec 04 '09 at 17:24
  • Thanks for the catch. I actually tried var instance = typeof(MyClass).ParseJson(text); not working – Codism Dec 04 '09 at 18:04

5 Answers5

28

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

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
9

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 Pitman
  • 12,990
  • 3
  • 41
  • 56
4

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...

pasx
  • 2,718
  • 1
  • 34
  • 26
2

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

LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 1
    and null instances of that type which is one of the redeeming values of ext. methods :) string val = null; val.IsNullOrEmpty() Sweet... – Brian Rudolph Dec 04 '09 at 21:09
-1

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.

Orhan
  • 420
  • 1
  • 6
  • 12
  • do you realize the op has an extension method but he wants to instantiate an object from an extension method on the type not on the instance. – Barreto Jul 29 '23 at 12:01