"Default" represents the default value of T parameter in generics instructions. In several cases, the default keyword is absolutely unknown and we think it’s unnecessary or its functionality makes it null. There are many development moments with the generics classes where default keyword can be useful.
Default keyword can make our work easier and can make the code safer.
Default(T)
This keyword returns the default value of type parameter.
These are the default values for the more important types inside of CLR,
- Classes - null
- Nullable<T> - null
- Numerics structs (int, double, decimal, etc) - 0
- DateTime structs - 01/01/0001.
- Char structs - empty char.
- Bool structs - false
Evaluation initializes T parameters
This is a very simple generic method example. This method has two ref parameters of T type and changes your values in the implementation.
- public static void ChangeValues<T>(ref T a, ref T b)
- {
- T _a = a;
- T _b = b;
- a = _b;
- b = _a;
- }
The ChangeValues method doesn't have a generic restriction filter so that T will be any type (reference type or value type)
If necessary validate if the parameters have been initialized (has a valid value different to initialize value), add a validation chunk,
- public static void ChangeValues<T>(ref T a, ref T b)
- {
- if(a.Equals(null) || b.Equals(null))
- {
- throw new ArgumentException("....");
- }
- T _a = a;
- T _b = b;
- a = _b;
- b = _a;
- }
We have a problem, because this implementation doesn’t verify the default value types.
It will be an incorrect execution:


sivanathan BalasubramanianPosted Jul 20, 2018, 7:41 PM
Very good article. Thank you
Juan Francisco Morales LariosPosted Sep 30, 2017, 5:42 AM
Thanks for your comment, Regards !!!
Hamid KhanPosted Sep 29, 2017, 9:40 AM
Nice.............................................