Why is there a class Nullable <T> and Nullable?
There is a structure Nullable<T>and there is another static class Nullablewith three static methods.
My question is: why are these static methods in a static class Nullablenot included in a Nullable<T>struct? What is the reason for their definition in two different types?
And there is an interface INullable. What is he doing?
It is standard practice with Generics to have a class with the same name as your common class with utilities related to the generic class. Because when you use a generic class, you cannot output generics in a type declaration, you will have more characters. See how it would be if static methods were placed in a common class:
Nullable<int?>.Compare(x, Y); var n = new Tuple<int,string>(10, "Text");against
Nullable.Compare(x, Y); var n = Tuple.Create(10, "Text");As an example, I included Tuple.
Interfaces and base classes are very useful in Generics, and since Nullable <> is a struct and structs cannot have a base class, we are left with interfaces. Now its use is possible.
{ int? a = 10; long? b = 10L; Process(a); Process(b); } private static void Process(INullable value) { if (value.IsNull) { // Process for null .. } else { // Process for value .. } }
, , nullable , , ,
public static bool Is<T>(this T variable,Type type) {
if (var != null) {
Type currentType = variable.GetType();
type = Nullable.GetUnderlyingType(type) ?? type;
while (currentType != typeof(object)) {
if (currentType == type) {
return true;
}
currentType = currentType.BaseType;
}
}
return false;
}
( nullable), nullable, , , , nullable.
Nullable.GetUnderlyingType(type), . , , , , .