Rob
Rob

Reputation: 2110

.Net class helper method

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.

Upvotes: 1

Views: 268

Answers (5)

Randolpho
Randolpho

Reputation: 56391

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.

Upvotes: 7

Rob Windsor
Rob Windsor

Reputation: 6859

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
   }
}

Upvotes: 1

ichiban
ichiban

Reputation: 6200

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){...}

}

Upvotes: 2

Kenan E. K.
Kenan E. K.

Reputation: 14111

What about an extension method?

public static void Randomize<T>(This IList<T> list)
{
    //randomize
}

Upvotes: 1

Greg Beech
Greg Beech

Reputation: 136627

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>.

Upvotes: 2

Related Questions