Sunday, November 12, 2017

Nullable in C#

Nullable is a special generic class meant to enable value types to be set to null.

Nullable<bool> nullableOfBool = false;
Nullable<int> nullableOfInt = 0;
Nullable<float> nullableOfFloat = 0.0f;

bool? nullableOfBool = false;
int? nullableOfInt = 0;
float? nullableOfFloat = 0.0f;

As you can see you can initialize them like if they were value types. Moreover, you can treat them like value types as long as you don't mix them with actual value types:

int? v1 = 1;
int? v2 = 7;
int? result = v1 + v2;

If for some reason you wanna access underlying type, you can do this by accessing Value property of Nullable:

int v1 = 1;
int? v2 = 7;
int result = v1 + v2.Value;

Or simply cast it to a corresponding value type:

int v1 = 1;
int? v2 = 7;
int result = v1 + (int)v2;

If you don't know if your nullable contains any value, use can check it using HasValue property.

1 comment:

  1. PineSucceed is a global full-cycle Software development company with niche expertise and a focus on the latest technologies. Since 2015, we have been helping companies achieve their goals with impactful, industry-specific software solutions. We are proud to earn the trust of world-class brands.

    ReplyDelete