0

I am attempting to extend a List. When using Visual Studio there are the different code hints for all the functions I can use with a List object. How can I extend the functionality of the List to show my new function?

public class ListExtensionHelper<T> : System.Collections.Generic.List<T>
{
    public List<T> AwesomeFunction<T>()
    {
    }
}

For the life of me I could not find anything online on how I would do it for a List

brenjt
  • 15,997
  • 13
  • 77
  • 118

2 Answers2

2

It sounds like you're looking for extension methods, rather than inheritance.

There are some really good examples here. There's also a really good library of extensions available here.

<soapbox>
One of my personal favorites that I use is this:

public static class StringExtensions
{
  public static bool IsNullOrEmpty(this string s)
  {
    return string.IsNullOrEmpty(s);
  }
}

It's ridiculously simple, but a huge pet peeve of mine is having to write:

if (string.IsNullOrEmpty(someVariable))

as opposed to:

if (someVariable.IsNullOrEmpty())

For me it's just a matter of being a natural construct of my native language. The built-in method sounds like:

object verb subject

whereas mine sounds like:

subject verb

It's probably silly, but when I want to act upon a subject it just makes more sense for me to start with the subject :)
</soapbox>

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
2

If you are trying to add AwesomeFunction as an extension method to a regular List object, then you need to define an extension method in a static class:

public static class ListExtensions
{
    public static List<T> AwesomeFunction<T>(this List<T> list)
    {
    }
}

Otherwise, the code you have should work; if you instantiate the ListExtensionHelper class, it should have all the functions of List as well as AwesomeFunction.

Lee D
  • 12,551
  • 8
  • 32
  • 34
  • It looks like I was just missing the `this` within the function paramenters. Thank you so much. – brenjt Jun 09 '11 at 15:55