Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create extension methods for Types

Tags:

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

like image 251
Codism Avatar asked Dec 04 '09 17:12

Codism


People also ask

How do you declare an extension method?

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.

What is used of extension methods and how do you create and use it?

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.

Can we create extension methods for static class?

No. Extension methods require an instance of an object.


1 Answers

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

like image 53
David Hedlund Avatar answered Oct 28 '22 15:10

David Hedlund