GetValueOrDefault Method for Nullable Value Types in C#
Nullable Value Types?
Value types in C# cannot have null value. However by using Nullable struct or ? we could achieve Nullability to value types.
In the following example, both the statements are valid Nullable value types.
GetValueOrDefault method is available to the nullable value types. This method retrieves the value of the variable if it’s not null, otherwise it returns the default value.
In the following example, the default value of int, which is 0 is returned by the GetValueOrDefault method as the nullable type has the value 0.
In the following example, notice that the nullable type has a value, in that case the GetValueOrDefault returns the value.
A custom default value could be returned by the GetValueOrDefault if the value is null. Notice the overloaded GetValueOrDefault method, which takes the default value as parameter.
Hope this post is useful.
Thanks for reading. Like Method Of Tried in Facebook.