C# shorthand: the type of variable declaration followed by the meaning of ?

  When I was writing a .Net project recently, I encountered a lot of interesting C# knowledge points (small markers or the way of writing elegant code), and today I took a note of an interesting variable declaration method: int? x=null;

  int? x means that a variable of type int that can be null is declared. Why do you need to do this? Because int is a value type variable, it cannot be null in theory, but we can allow x to be null in this way.

  what does x being null do? First, you can make this judgment:

if(x==null){}
if(x!=null){}

  Determine whether the value of a method call is obtained? Or is a variable that flags a change changed? etc. And, you can also make the following calls through such variables:

using System;

class NullableExample
{
  static void Main()
  {
      int? num = null;

      // Is the HasValue property true?
      if (num.HasValue)
      {
          Console.WriteLine("num = " + num.Value);
      }
      else
      {
          Console.WriteLine("num = Null");
      }

      // y is set to zero
      int y = num.GetValueOrDefault();

      // num.Value throws an InvalidOperationException if num.HasValue is false
      try
      {
          y = num.Value;
      }
      catch (InvalidOperationException e)
      {
         Console.WriteLine(e.Message);
      }
   }
}

  and to determine if it has a value:

int? x = 10;
if (x.HasValue)
{
    System.Console.WriteLine(x.Value);
}
else
{
    System.Console.WriteLine("Undefined");
}

To sum up, the significance of this naming method is that if we use a value variable to identify the success of our method call, we may encounter that although the call fails, the expected failure prompt will still not appear ( Because value variables have default values).

Finally, go to the official documentation portal: Nullable Types (C# Programming Guide)

PS: This value variable also supports packing and unpacking (the definition of packing \ unpacking can be found under Baidu), give an official sample code:

The behavior of nullable types when boxed provides two advantages:

  • Nullable objects and their boxed counterpart can be tested for null:
bool? b = null;  

object boxedB = b;
if (b == null)
{
// True.
}
if (boxedB == null)
{
// Also true.
}


* Boxed nullable types fully support the functionality of the underlying type:

double? d = 44.4;
object iBoxed = d;
// Access IConvertible interface implemented by double.
IConvertible ic = (IConvertible)iBoxed;
int i = ic.ToInt32(null);
string str = ic.ToString();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324467220&siteId=291194637