views:

107

answers:

5

Is there a way to add a method to a class, but allow it still be inherited by the base class?

I have the following

public class ListWithRandomize<T> : List<T> {
   public void Randomize() { // Randomize function}

}

I'm going to have a bunch of List objects that will need to be randomized. Is it possible to have a List object that I can just "Make" into a ListWithRandomize object? I suppose I could just make the randomize function static and have it take a List<> as a parameter, but I'd like to have it as a method of the class.. if possible.

Thanks.

+7  A: 

An extension method is the only way you can add a method to a class when you don't have access to the source.

Keep in mind that an extension method is not an actual member of a type -- it just looks like that in your source code. It cannot access private or internal variables -- at least, not without reflection, but you probably don't want to do that.

I suppose I could just make the randomize function static and have it take a List<> as a parameter, but I'd like to have it as a method of the class.. if possible.

In that case, an extension method is probably your best bet.

Randolpho
I love this board. Thanks guys...
Rob
That's why we're here.
Randolpho
+2  A: 

Sounds like you want an extension method, e.g.

public static void Randomize(this List<T> list)
{
    // ... 
}

This is a static method that will appear to be an instance method on List<T>.

Greg Beech
+1  A: 

What about an extension method?

public static void Randomize<T>(This IList<T> list)
{
    //randomize
}
kek444
+2  A: 

I think that C# 3.0 Extension method would do what you are trying to accomplish here.

public static class MyListExtension {
  public static void Randomize(this List<T> list){...}

}
ichiban
+1  A: 

Extension Methods. You can add the Randomize method to List. This code was written here so it may not complile. It should give you a start though.

public static class Extenstions
{
   public static List<T> Randomize<T>(this List<T> list)
   {
      // randomize into new list here
   }
}
Rob Windsor