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

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   

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.