0

When a new object of class Foo is created, the constructor is supposed to create a new folder and a new file based on the object properties. But I get NullException (param: path2)?

I found that the object properties has Null value when the constructor is called. But I gave the properties values when I created the object? What am I missing?

My Foo class:

public class Foo
{
    public string Bar { get; set; }
    public string Baz { get; set; }
    public string Source { get { return Path.Combine(Qux, Baz, Bar); } }
    private string Qux { get { return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } }

    public Foo()
    {
        // Use property values to find or create Directory and File
        if (!Directory.Exists(Path.Combine(Qux, Baz))) Directory.CreateDirectory(Path.Combine(Qux, Baz));
        if (!File.Exists(Source)) File.Create(Source);
    }
}

In my Main class:

// Create a new Foo object with following property values
Foo foo = new Foo { Baz = "corge", Bar = "grault" };
user5825579
  • 105
  • 3
  • 15
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dmitry Nov 14 '16 at 15:34
  • 4
    With that syntax, the constructor runs *before* the properties are assigned to. Since you're using them in the constructor's body, you're out of luck. Maybe make them constructor arguments instead? – Frédéric Hamidi Nov 14 '16 at 15:35
  • 2
    Possible duplicate of http://stackoverflow.com/questions/17327266/constructor-vs-object-initializer-precedence-in-c-sharp - Constructor vs Object Initializer Precedence in C# – KMoussa Nov 14 '16 at 15:36

1 Answers1

9

But I gave the properties values when I created the object?

No you didn't. (Though admittedly it may be a little unintuitive if you're new to the syntax.)

The code is expecting those to be supplied in the constructor. But you have a parameterless constructor:

public Foo()
{
    //...
}

So when that constructor executes those properties haven't been set and have their default values.

Add the parameters to the constructor itself:

public Foo(string baz, string bar)
{
    Baz = baz;
    Bar = bar;
    //...
}

And then supply them to the constructor:

new Foo("corge", "grault")

What you're doing here:

Foo foo = new Foo { Baz = "corge", Bar = "grault" };

Is the equivalent of this:

Foo foo = new Foo();
foo.Baz = "corge";
foo.Bar = "grault";

The constructor is being called first, before the parameters are set.

David
  • 208,112
  • 36
  • 198
  • 279