Extend an existing or custom class

Writing a extension for an existing class such as string.DoSomethingHere()

I usually run my database logic through Linq and a dbi.cs class for my database interaction. The dbml file will produce all of my custom classes which is great, but, I wanted to add some custom extensions. Looking at that code created by the dbml is overwhelming and I would rather not go poking around in there, so, I decided to make my own extensions, it's not a difficult process.

I had a class named ticket and I wanted to add an extension IEnumerable<ticket>.open() which would list all open tickets. Now, to get in to my calss structure and all of that would be a waste of time, so I will show how to do this with something that is a bit more familiar and likely useful, I am going to extend the string class with string.capitalizeFirstLetter() which would turn:

a senTENCE like this ONE hErE

into one like this

A Sentence Like This One Here

And yes, I know there is the CSS text-transform, but that isn't the point, it is the method I am showing.

First thing is first, make a new class called MyCustomExtensions.cs or something like that. Next, make sure to declare the class as a public static class. Now make a public static string method. normally in a method you would take a string input like this:

methodName(string someString)

For extensions, you do them slightly different like this:

methodName(this string someString)

Notice that this is now ahead of string, that will tell you program to 'look' for this extension whever a single string is used; it will also populate your intellisense in Visual Studio.

That is really the only big difference, now you just treat it like any other method. This is my full example class:

using System.Collections.Generic;
using System.Text;

/// <summary>
/// Custom Class Extensions
/// </summary>

public static class custom_extensions
  public static string CapitalizeFirstLetters(this string s)
    string[] splitString = s.Split(new char[] { ' ' });
    List capitalized = new List();
    foreach (string word in splitString)
      string add;
      if (word.Length == 1) add = word.ToUpper();
      else if (word.Length == 0) add = string.Empty;
      else add = word.Substring(0, 1).ToUpper() + word.Substring(1, word.Length - 1);
    StringBuilder sb = new StringBuilder();
    foreach (string word in capitalized) sb.Append(word + " ");
    sb.Remove(sb.Length - 1, 1); return sb.ToString();
Comments are closed