Recommendation 35: Use default to specify an initial value for a generic type variable
Some algorithms, such as the Find algorithm for generic collection list<t>, may be looking for a value type, or possibly a reference type. Within this algorithm, we often specify default values for these value types or reference type variables. So the problem is that the default initial value of a value type variable is a value of 0, whereas the default initial value of a reference type variable is a null value, which obviously causes the following compilation error:
Public T func<t>() { null; return t; }
Cannot convert null to type parameter ' T ' because it may be a non-nullable value type. Consider using "Default (T)" instead.
Public T func<t>() { 0; return t; }
The type "int" cannot be implicitly converted to "T".
So the above code should read:
Public T func<t>() { default(t); return t; }
Thus, if it encounters t as an integer at run time, the runtime assigns it a value of 0, and if T is a reference type such as a person at run time, it will be assigned a null value.
List<t> 's Find method source code is:
[__dynamicallyinvokable] PublicT Find (predicate<t>match) { if(Match = =NULL) {throwhelper.throwargumentnullexception (exceptionargument.match); } for(inti =0; I < This. _size; i++) { if(Match ( This. _items[i])) { return This. _items[i]; } } return default(T);}
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 35: Use default to specify initial values for generic type variables