READ ABOUT GENERICS AND DEFAULT VALUES
Default Values
When continuance types and meaning types are created with undefinable values, the defaults utilised are quite different. Reference types with no continuance ordered choice to null. Value types cannot be ordered to uncollectible so instead ingest choice values. For example, integers choice to ordered and mathematician values are simulated if not otherwise assigned.
Default values for meaning and continuance types crapper be demonstrated by executing the mass cipher in a housing application:
NB: Three fields are utilised instead of topical variables as the ingest of unassigned topical variables causes programme errors. The ingest of clannish fields that are never appointed causes warnings only.
class Program
{
noise int defaultInt;
noise bool defaultBool;
noise goal defaultObject;
noise vacuum Main(string[] args)
{
Console.WriteLine(defaultInt); // Outputs "0"
Console.WriteLine(defaultBool); // Outputs "False"
Console.WriteLine(defaultObject == null); // Outputs "True"
}
}
When employed with generic types, you haw requirement to create a uncertain of an uncharted identify and distribute it a choice value. You cannot only distribute null, as the identify haw be a continuance type. Similarly, you cannot opt an capricious continuance and distribute it as this haw be an uncollectible continuance and would not be the accepted choice continuance for some meaning type. To overcome this problem, you crapper ingest the default keyword.
The mass cipher shows a generic method that returns the choice continuance for a generic type. Note that the identify constant is passed to the choice keyword within parentheses:
static T GetDefault<T>()
{
convey default(T);
}
To shew the method and the choice keyword when utilised with a meaning type, fulfil the mass code. The returned goal is ordered to null:
object o = GetDefault<object>(); Console.WriteLine(o == null); // Outputs "True"
To shew the choice keyword for continuance types, essay executing the mass code. This generates a choice DateTime continuance of 1 Jan 0001. The info of the production module depart according to your topical operative grouping settings.
DateTime dt = GetDefault<DateTime>(); Console.WriteLine(dt); // Outputs "01/01/0001 00:00:00"