A senior member here gave me this code:
public static string Truncate(this string value, int maxChars)
{
return value.Length <= maxChars ? value : value.Substring(0, maxChars) + " ..";
}
He said to use it as an extension method. But where do I put this method? It looks like it adds something to .Net
Consider a class named
StringExtensionslike so:Be sure that whatever namespace you put this class in, you include a
usingdeclaration for that namespace.Thus, for a full example:
StringExtensions.cs:Program.cs:By the way, you are not adding it to .NET. You are not even adding a new method to the class
String. Rather, it’s a compiler trick that makes static methods living in static classes with their first parameter declared asthis *TypeName* *valueParameter*where*TypeName*is the name of a type, and*valueParameter*is the name of the parameter can be made to appear as an instance method on instances of the type with type name*TypeName*. That isis translated by the compiler into