Monday, 6 January 2020

Default value List for different data type in C#

In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds by default. I was working on a project and used following code
int score; If (somecondition == true) score = somevalue; 
And I was expecting if condition is true then score will be assigned otherwise it would be null but I was wrong because default value for an int variable is zero (0). Finally I changed my code, and forcibly make my score variable to nullable.
Int? score; If (somecondition == true) score = somevalue; 
On the other hand String is by default null and not an empty string also string not a value type in C# but its a reference type.
Here is the some mostly used data type and their default values
  1.  DATE TYPE  |  DEFAULT VALIE
  2. ------------------------------------
  3.  String     |  null
  4.  bool       |  false
  5.  char       |  '\0'
  6.  decimal    |  0.0M
  7.  double     |  0.0D
  8.  enum       | The value produced by the expression (E)0,
  9.                       where E is the enum identifier.
  10.  float      |  0.0F
  11.  int        |  0
  12.  long       |  0L
  13.  sbyte      |  0
  14.  short      |  0
  15.  struct     |  The value produced by setting all value-type fields to their
  16.                    default values and all reference-type fields to null.
  17.  uint       |  0
  18.  ulong      |  0
  19.  ushort     |  0

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...