Problem:
You have a generic class that contains a variable that defines type parameters by the class itself. Due to constraints on generic objects, you want this variable to be initialized to its default value.
Solution:
A very simple method: you only need to use the default keyword to initialize the default value:
Public class defaultvalueexample <t>
{
T data = default (t );
Public bool isdefaultdata ()
{
T temp = default (t );
If (temp. Equals (data ))
{
Return (true );
}
Else
{
Return (false );
}
}
Public void setdata (T Val)
{
Data = val;
}
}
The code for using this class can be referred here:
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace setdefaultvalueexample
{
Class Program
{
Static void main (string [] ARGs)
{
Defaultvalueexample <int> DV = new defaultvalueexample <int> ();
// Check whether it is set to the default value. If yes, true is returned.
Bool isdefault = DV. isdefaultdata ();
Console. writeline ("initial data:" + isdefault );
// Set Data
DV. setdata (100 );
// Check again. At this time, false should be returned.
Isdefault = DV. isdefaultdata ();
Console. writeline ("Set Data:" + isdefault );
}
}
Public class defaultvalueexample <t>
{
T data = default (t );
Public bool isdefaultdata ()
{
T temp = default (t );
If (temp. Equals (data ))
{
Return (true );
}
Else
{
Return (false );
}
}
Public void setdata (T Val)
{
Data = val;
}
}
}
When initializing a variable of the same type of parameter, you cannot just set these variables to null. If this variable is of the value type, such as Int or char, what would it be? It cannot run because the value type cannot be null. You may think of a nullable type, such as long? OrNullable <long> can be set to null. However, the compiler cannot know what type parameters the user will use to construct this type.
The default keyword allows you to tell the compiler that the default value of this type will be used during compilation. If the type parameter is a numeric value (INT, long, decimal), the default value is 0. If it is a reference type, the default value is null. If it is a struct, the default value of this struct is set to 0 or Null Based on the type of each field.