Skip to main content

Cannot declare instance member in a static class

In This Article

CodeRush Classic shows the Cannot declare instance member in a static class code issue if the current non-static member is declared in a static class.

#Fix

Add the static keyword to the current member declaration or make the class non-static.

#Purpose

Highlights the member declaration statements, which would cause the Cannot declare instance member in a static class compilation error.

#Example

static class MyClass
{
    public static string Text { get; set; }
    public string InvertText()
    {
        string result = string.Empty;
        for (int i = MyClass.Text.Length-1; i >= 0; i--)
            result += MyClass.Text[i];
        return result;
    }
}

Fixes:

static class MyClass
{
    public static string Text { get; set; }
    public static string InvertText()
    {
        string result = string.Empty;
        for (int i = Text.Length-1; i >= 0; i--)
            result += Text[i];
        return result;
    }
}
class MyClass
{
    public static string Text { get; set; }
    public string InvertText()
    {
        string result = string.Empty;
        for (int i = MyClass.Text.Length-1; i >= 0; i--)
            result += MyClass.Text[i];
        return result;
    }
}