Skip to main content

Cannot create an instance of static class

In This Article

CodeRush Classic shows the Cannot create an instance of static class code issue if an instance creation statement references a static class.

#Fix

Remove the instance creation statement. Static class members are accessed by using the class name itself.

#Purpose

Highlights the instance creation statements, which would cause the Cannot create an instance of the static class compilation error.

#Example

static class MyClass
{
    public static void OutputText(string text)
    {
        Console.Write(text);
    }
}
class TestClass
{
    public TestClass()
    {
        MyClass objVar = new MyClass();
        objVar.OutputText("TestClass object created");
    }
}

Fix:

static class MyClass
{
    public static void OutputText(string text)
    {
        Console.Write(text);
    }
}
class TestClass
{
    public TestClass()
    {
        MyClass.OutputText("TestClass object created");
    }
}