"this" in function parameter

Take a look at some sample code for HtmlHelpers, and I see ads that look like this:

public static string HelperName(this HtmlHelper htmlHelper, ...more regular params ) 

I don’t remember the appearance of this type of construction being anywhere else - can someone explain the purpose of this? I thought that declaring something public static meant that the class didn't need to be instantiated - so what is “this” in this case?

+63
c # parameters asp.net-mvc
Jun 15 '10 at 12:49
source share
5 answers

This is the syntax for declaring extension methods, a new feature in C # 3.0.

The extension method is part code, the magic part compiler, where the compiler, using intellisense in Visual Studio, shows that your extension method is actually available as an instance method for the object in question.

Let me give you an example.

There is no method in the String class called GobbleGobble, so create an extension method:

 public static class StringExtensions { public static void GobbleGobble(this string s) { Console.Out.WriteLine("Gobble Gobble, " + s); } } 

The class name is just my naming convention, there is no need to call it that, but it should be static, like the method.

After declaring the above method, you can enter the following in Visual Studio:

 String s = "Turkey Baster!"; s. 

after the period, wait for intellisense and note that there is a GobbleGobble method, execute the following code:

 String s = "Turkey Baster!"; s.GobbleGobble(); 

It is important . The class in which the extension method is declared must be accessible to the intellisense compiler and processor so that intellisense displays this method. If you manually enter GobbleGobble and use the Ctrl + shortcut . , this will not help you get the correct use of directives in the file.

Note that the method parameter has disappeared. The compiler will silently navigate important bits that:

 String s = "Turkey Baster!"; s.GobbleGobble(); ^ ^ | +-- the compiler will find this in the StringExtensions class | +-- will be used as the first parameter to the method 

Thus, the above code will be converted by the compiler to the following:

 String s = "Turkey Baster!"; StringExtensions.GobbleGobble(s); 

So, during the call, there is nothing magical about this, it is just a call to the static method.

Please note that if your extension method declares more than one parameter, only the first one supports the this modifier, and the rest should be specified as part of the method call as usual:

 public static void GobbleGobble(this string value, string extra) { | | ... | | } | | | | +--------------------------------------------+ | | | v | s.GobbleGobble("extra goes here"); | ^ | | | +-----------------------------------+ 

Extension methods were added in part because of Linq, where Linq C # syntax will look for suitable named extension methods for objects in the game, which means that you can "embed" Linq support in any type of class by simply declaring the correct extension methods. Of course, full Linq support is a lot of work, but it is possible.

In addition, the extension methods themselves are really useful, so read on it.

Here are some links:

+157
Jun 15 '10 at 12:57
source share

Used for extension methods. You basically stick the Helpername to the htmlHelper object so you can say:

 new HtmlHelper().HelperName(...more regular params); 
+6
Jun 15 '10 at 12:50
source share

After the extension methods, I used them like crazy .. here are a few I use all the time.

 public static T ChangeType<T>(this object obj) { return (T)Convert.ChangeType(obj, typeof(T)); } 

It works like this.

 int i = "123".ChangeType<int>(); bool valid = "bool".ChangeType<bool>(); int id = dataSet.Tables[0].Rows[0]["Id"].ChangeType<int>(); 

Yes, it appears on every single object, it can be annoying, but since I use it for almost every data type, it helps just attach it to the object, rather than duplicating it for each data type.

 public static string ToXml(this object serializableObject) { var aMemStr = new MemoryStream(); try { var serializer = new XmlSerializer(serializableObject.GetType()); serializer.Serialize(new XmlTextWriter(aMemStr, null), serializableObject); return Encoding.UTF8.GetString(aMemStr.ToArray()); } finally { if (aMemStr != null) { aMemStr.Dispose(); } } } string xml = dataSet.ToXml(); public static T ToObject<T>(this string xmlString) { var aStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)); try { return (T)new XmlSerializer(typeof(T)).Deserialize(aStream); } finally { if (aStream != null) { aStream.Dispose(); aStream = null; } } } DataSet dataSet = xml.ToObject<DataSet>(); 
+6
Jun 15 2018-10-15
source share

This will be an extension method. They allow you to “extend” a class using static methods that live outside the original class.

For example, let's say you have a useful string method that you use all the time ...

 public int CountAllAs(string orig) { return orig.ToLowerInvariant().ToArray().Count(c => c == 'a'); } 

And you call it ...

 string allAs = "aaaA"; int count = CountAllAs(allAs); 

It's not so bad. But with a little change, you can make it an extension method, and the call will be a bit prettier:

 public static int CountAllAs(this string orig) { return orig.ToLowerInvariant().ToArray().Count(c => c == 'a'); } 

And then call him ...

 string allAs = "aaaA"; int count = allAs.CountAllAs(); 
+4
Jun 15 '10 at 12:59
source share

Extension Methods ...

... are a fantastic way to enable features as if you were using a decorator drawing , but without the pain of refactoring all your code or using a different name of a common type.

 public static class Extensions { public static string RemoveComma(this string value) { if (value == null) throw new ArgumentNullException("value"); return value.Replace(",", ""); } } 

Thus, you can use this code anywhere in the application.

 Console.WriteLine("Hello, My, Friend".RemoveComma()) >> Hello My Friend 

Thus, the this attribute means the type that is added by the addition, and allows you to work with the value as if it were passed as a parameter.

+3
Jun 15 '10 at 13:04 on
source share



All Articles