user195166
user195166

Reputation: 439

object initialisation can determine member was defaulted or not?

If I have a class

class widget {
    public int theNum;
    public string theName;
}

and I initalise like this

widget wgt = new widget { thename="tom" };

theNum will be zero.

Is there a way for me to examine the instance wgt to determine that the member theNum was defaulted i.e. excluded from the object initialisation?

Upvotes: 0

Views: 40

Answers (3)

Fede
Fede

Reputation: 44028

Instead of int use an int? (which is a short-hand for System.Nullable<int>. then, if nobody initializes it to a valid int, its going to be null.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499790

One option would be to change theNum to be an int? instead... then the default value would be the null value, which is different from 0.

I would expect those to be public properties rather than public fields, mind you - in which case you could make the property type int, keeping int? as the backing field type and providing some other way of checking for initialization, by testing whether the field value was null.

Upvotes: 3

Jon
Jon

Reputation: 437336

As long as theNum is a field you cannot tell if it was left uninitialized or if it was explicitly initialized to its default value (which in this case is 0, but could be different if you had public int theNum = 42).

If theNum were a property then you could set a flag from within the property setter that allowed you to determine if the setter was invoked, no matter what value you set the property to. For example:

class widget {
    private int theNum;
    private bool theNumWasSet;
    public string theName;

    public int TheNum
    {
        get { return theNum; }
        set { theNumWasSet = true; theNum = value; }
    }
}

Upvotes: 3

Related Questions