1

I am trying to implement grenade's response from thsi thread on how to randomize a list: Randomize a List<T>. The solution includes creating an extended list. Here is the exact way it's written in my own code:

    static class MyExtensions
{
    static readonly Random Random = new Random();
    public static void Shuffle<T>(this IList<T> list)
    {
        Random rng = new Random();
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}

The problem with this is that when I try to run the method in a button click event on a list I created when said event is triggered, VS does not recognize the method and produces this error:

System.Collections.Generic.IList does not contain a definition for 'Shuffle' and no extension method 'Shuffle' accepting a first argument of type 'System.Collections.Generic.IList could be found..."

Here is my attempted usage for reference:

    public void Button1_Click(object sender, EventArgs e)
    {


    IList<int> dayList = new List<int>();
    for (int i = 0; i < 32; i++)
    {
        dayList.Add(i);
    }

    dayList.Shuffle();

    More code...

    }

I've searched these boards and found that I need to declare the namespace in which the extension method is, but mine is inline with the rest of my page, so there is no namespace to declare. Suggestions?

Community
  • 1
  • 1
erstaples
  • 1,986
  • 16
  • 31

2 Answers2

1

are you sure you are importing MyExtensions in the form class where you are using it.

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

Search for this in your MyExtensions file:

namespace MyApp.Namespace
{

Now add this at the very top of your form:

using MyApp.Namespace;

MyApp.Namespace is only a placeholder for your namespace, of course. If your extensions are in different project you would have to add a reference to this project. You may also want to make your MyExtensions public.

Jobo
  • 1,084
  • 7
  • 14
  • The MyExtensions extension is inline with the rest of my page, nested in the same – erstaples Mar 13 '13 at 11:32
  • 1
    Then change it.. Apparently there is no way to do it your way: http://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class – Jobo Mar 13 '13 at 11:47
  • That's a helpful article. Okay, with that in mind, I'll just create a separate namespace in my current project and call it like any other namespace. Thanks! – erstaples Mar 13 '13 at 12:39