Default expression

The C # specification first says:

If the default type of an expression is evaluated at runtime prior to the reference type, the null result is converted to that type. If the type in the default expression is evaluated at runtime to the type of value, the result is the value of the default value (ยง4.1.2).

So, it seems that the default expression is evaluated at runtime ... but after it says:

The default value is a constant expression (ยง7.19) if type is a reference type or a type parameter, which is known to be a reference type (ยง10.1.5). In addition, the default expression is a constant expression if the type is one of the following value types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any type of enumeration.

since there can be a defaultconstant expression, therefore compilation time is estimated if only the type of runtime is checked?

For example, if I write something like:

J k = default(J);

where Jis the type parameter, only at runtime, when we provide the type of the argument, we can know whether the Jreference type or value type. So what happens during compilation?

+4
3

( ):

  • - (ยง7.19) , - , , ,

, ( ) ( , where T : class default(SomeClass)), . :

  • , , : sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool

, - default(sbyte) default(short).

, :

void Main()
{
    var x = default(byte);
    var y = default(M);
}

public struct M { }

:

IL_0000:  nop         
IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     // x
IL_0003:  ldloca.s    01 // y
IL_0005:  initobj     UserQuery.M
IL_000B:  ret  

byte 0, initobj M struct.

+3

, J, , , , foo<J>,

foo<int> myfoo =new foo<int>(); // this is also evaluated at compile time
myfoo.bar(); // the compiler invokes the bar method of the foo<int> type and thus returns default(int)
0

, , , .

default(string) default(int), default(T) ( ) T ( , ).

, .

, jit-time, , , , , , , :

if (default(T) == null)
{
   // code for reference-type or Nullable<> types of T
}
else
{
  // code for non-nullable value types of T
}

, .

0

Source: https://habr.com/ru/post/1621980/


All Articles