user5825579 user5825579 - 24 days ago 9
C# Question

C# Create new object with property values in constructor return Null

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" };

Answer

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.