'"this" in function parameter
Looking at some code examples for HtmlHelpers, and I see declarations that look like:
public static string HelperName(this HtmlHelper htmlHelper, ...more regular params )
I can't remember seeing this type of construct any where else - can someone explain the purpose of the "this"? I thought that by declaring something public static meant that the class did not need to be instantiated - so what is "this" in this case?
Solution 1:[1]
After extension methods, I've been using them like crazy.. here is a few I use constantly..
public static T ChangeType<T>(this object obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
Works like this..
int i = "123".ChangeType<int>();
bool valid = "bool".ChangeType<bool>();
int id = dataSet.Tables[0].Rows[0]["Id"].ChangeType<int>();
Yeah, it shows up on every single object, can be annoying but since I use this for pretty much every data type, it helps to just attach it an object rather than duplicating it for every data type possible.
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>();
Solution 2:[2]
It is used for extensionmethods. Basically you 'glue' the Helpername to the htmlHelper object so you can say:
new HtmlHelper().HelperName(...more regular params);
Solution 3:[3]
That would be an Extension Method. They allow you to "extend" a class via static methods that live outside the original class.
For example, say you have a helpful 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);
That's not too bad. But with a small change, you could make it an Extension method and the call would be a little prettier:
public static int CountAllAs(this string orig)
{
return orig.ToLowerInvariant().ToArray().Count(c => c == 'a');
}
And then call it...
string allAs = "aaaA";
int count = allAs.CountAllAs();
Solution 4:[4]
...are a fantastic way to include functionality like if you where using the decorator pattern, 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(",", "");
}
}
So you can use this code, anywhere in you app.
Console.WriteLine(“Hello, My, Friend”.RemoveComma())
>> Hello My Friend
So the this command attribute mean the type that the extension will be “added”, and let you work with the value as if it was passed as parameter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jaekie |
| Solution 2 | Henrik Gering |
| Solution 3 | Justin Niessner |
| Solution 4 | Fraga |
