22
votes

Error at:

public partial class Form2 : Form

Probable cause:

public static IChromosome To<T>(this string text)
{
    return (IChromosome)Convert.ChangeType(text, typeof(T));
}

Attempted (without static keyword):

public IChromosome To<T>(this string text)
{
    return (IChromosome)Convert.ChangeType(text, typeof(T));
}
4
Just when I thought that was actually a good error message. - Christian.K

4 Answers

44
votes

If you remove "this" from your parameters it should work.

public static IChromosome To<T>(this string text)

should be:

public static IChromosome To<T>(string text)
19
votes

The class containing the extension must be static. Yours are in:

public partial class Form2 : Form

which is not a static class.

You need to create a class like so:

static class ExtensionHelpers
{
    public static IChromosome To<T>(this string text) 
    { 
        return (IChromosome)Convert.ChangeType(text, typeof(T)); 
    } 
}

To contain the extension methods.

3
votes

My issue was caused because I created a static method inside the partial class:

public partial class MainWindow : Window{

......

public static string TrimStart(this string target, string trimString)
{
    string result = target;

    while (result.StartsWith(trimString)){
    result = result.Substring(trimString.Length);
    }

    return result;
    }
} 

When I removed the method, the error went away.

1
votes

Because your containing class is not static, Extension method should be inside a static class. That class should be non nested as well. Extension Methods (C# Programming Guide)