C # - check if integer property is set

I am checking some properties and I need to know if long or integer values ​​are set by other layers.

For example, this class ::

public class Person { public int Age {get;set;} } 

When I install a new instance of Person , Age gets the value 0. But I have to check if Age has been set, because Age can be zero (not in this context).

One solution that I was thinking about is to use int as an integer ( public int? Age ), and the constructor of Person is set to Age as zero.

But I try to avoid this because I will need to change too many classes to check if Age.HasValue exists and use it as Age.Value .

Any suggestions?

+7
source share
3 answers

Int is initialized to 0 by default; Assuming you don't want to use int? which is perfect for you. You can check this, or you can have a flag and a support field:

 private int _age; public int Age { get { return _age; } set { _age = value; _hasAge = true; } } public bool HasAge { get { return _hasAge; } } 

As suggested above, you can initialize it to an invalid state:

 private int _age = -1; public int Age { get { return _age; } set { _age = value; _hasAge = true; } } public bool HasAge { get { return _age != -1; } } 

Or just break and use int?

 public int? Age { get; set; } public bool HasAge { get { return Age.HasValue; } } 

For backward compatibility with your code, can you disable its int? without exposing it to:

 private int? _age; public int Age { get { return _age.GetValueOrDefault(-1); } set { _age = value; } } public bool HasAge { get { return _age.HasValue; } } 
+19
source

There is no difference between a field (or an automatically implemented property) that is explicitly set to its default value and which has never been set.

A Nullable<int> is definitely the way to go, but you will need to consider the cleanest API to use.

For example, you can:

 public class Person { private int? age; public int Age { // Will throw if age hasn't been set get { return age.Value; } // Implicit conversion from int to int? set { age = value; } } public bool HasAge { get { return age.HasValue; } } } 

This will allow you to read Age directly in places that suggest they were installed - but check this when they want to be careful.

+5
source

Whatever template you use, you will need to ask the install request before you get the value, so ...

Use a field with a null int? age value int? age int? age , which uses your get / set properties, and request the IsAgeSet property:

 public class Person { private int? age; public int Age { get {return age.Value;} // will fail if called and age is null, but that your problem...... set {age = value;} } public bool IsAgeSet { get {return age.HasValue;} } } 
+1
source

All Articles