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" };
3
  • 1
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Nov 14, 2016 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? Commented Nov 14, 2016 at 15:35
  • 2
    Possible duplicate of stackoverflow.com/questions/17327266/… - Constructor vs Object Initializer Precedence in C# Commented Nov 14, 2016 at 15:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.