Search code examples
c#classopenxmlinstantiation

CS0426 when creating an object - How to understand error


I got a CS0426 compiler error when trying to open an Excel using SpreadsheetDocument class from DocumentFormat.OpenXml.Packaging namespace.

I realized that this was because I was using new and, for some reason, the compiler didn't like it.

Why can't I create an instance of the object using new?

//Error CS0426
using (SpreadsheetDocument goldenFile = new SpreadsheetDocument.Open(goldenPath, true));

//Ok code
using (SpreadsheetDocument goldenFile = SpreadsheetDocument.Open(goldenPath, true));

Solution

  • Judging by its name and context, the SpreadsheetDocument.Open method opens a new spreadsheet file for you to read/write from/to.

    This should be the correct way to use this API:

    using (SpreadsheetDocument goldenFile = SpreadsheetDocument.Open(goldenPath, true)) {
        ...
    }
    

    You need to understand that not every class needs to be created by you writing the word new and directly calling the constructor. Sometimes, in this case for example, the instance of SpreadsheetDocument is probably created somewhere inside the Open method. The Open method simply returns the new instance, so that you can assign it to a variable (goldenFile in this case).

    You can write a class that gets created with a static method too:

    class Foo {
        // properties...
    
        // private constructor
        private Foo() { ... }
    
        public static GiveMeAFoo() {
            return new Foo();
        }
    }
    

    I can now create an instance of Foo without directly using new:

    var foo = Foo.GiveMeAFoo();
    

    Something similar is happening inside Open.


    The compiler gives off the error CS0426 because it thinks like this:

    I see that you are using the new operator, so you are creating a new instance of a type. What type is it that you are creating? Let's see... It's SpreadsheetDocument.Open! But wait a minute! That's not a type! I can't find a type called Open in SpreadsheetDocument!

    Hence the error:

    The type name 'Open' does not exist in the type 'SpreadsheetDocument'.