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
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
No. Extension methods require an instance of an object.
The short answer is it cannot be done; extension methods need to work on an instance of something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With