Extension Methods, ie String.Truncate
Posted on: Thu Nov 05 17:20:03 -0800 2009. Updated on: Thu Nov 05 17:22:29 -0800 2009.
Category: DotNet
Category: DotNet
Extension Methods can be pretty cool, but you should watch out what you use them for. They are used to extend existing classes, like the String or int class. In this example I will show a quick Truncate extension to the String class so you could simply go myString.Truncate(30)
public static class MyExtensions
{
public static string Truncate(this String str, int maxLength)
{
if (str.Length > maxLength)
{
str = str.Substring(0, maxLength);
}
return str;
}
}
// usage
String car = "pedoloco";
car.Truncate(3); // ped
car.Truncate(100); // pedoloco