Tutorial by Examples

For null values: Nullable<int> i = null; Or: int? i = null; Or: var i = (int?)null; For non-null values: Nullable<int> i = 0; Or: int? i = 0;
int? i = null; if (i != null) { Console.WriteLine("i is not null"); } else { Console.WriteLine("i is null"); } Which is the same as: if (i.HasValue) { Console.WriteLine("i is not null"); } else { Console.WriteLine("i is null&quot...
Given following nullable int int? i = 10; In case default value is needed, you can assign one using null coalescing operator, GetValueOrDefault method or check if nullable int HasValue before assignment. int j = i ?? 0; int j = i.GetValueOrDefault(0); int j = i.HasValue ? i.Value : 0; The ...
The .GetValueOrDefault() method returns a value even if the .HasValue property is false (unlike the Value property, which throws an exception). class Program { static void Main() { int? nullableExample = null; int result = nullableExample.GetValueOrDefault(); C...
public bool IsTypeNullable<T>() { return Nullable.GetUnderlyingType( typeof(T) )!=null; }
public class NullableTypesExample { static int? _testValue; public static void Main() { if(_testValue == null) Console.WriteLine("null"); else Console.WriteLine(_testValue.ToString()); } } Output: null
Any nullable type is a generic type. And any nullable type is a value type. There are some tricks which allow to effectively use the result of the Nullable.GetUnderlyingType method when creating code related to reflection/code-generation purposes: public static class TypesHelper { public stat...

Page 1 of 1