Special Data Types

Enumerated Data Type(enum):

You have different data types in C# but what if you have your own type? Yes, it’s true, the magic of having your own defined type in C#. Enumeration provides such a functionality which helps you create a distinct type that contains a set of named constants and the set of the named constants is called an enumeration list. Enumeration is done by usinghe tkeyword enum. You define a set of constants inside the enumeration list under the enum keyword with the enumerated name. You can use the enumerated constants by calling it using the enumerated name you have provided. The syntax for enumerated data type is:

  1. enum < enum_name >  
  2.   
  3.     {  
  4.   
  5.         Enumeration list;  
  6.   
  7.     };  
  8.   
  9. Example:  
  10.   
  11.     enum MyData  
  12.   
  13. {  
  14.     Name,  
  15.     Address,  
  16.     DOB,  
  17.     Education  
  18. };  

While calling these  enum constants, we call it using the enum_name like MyData.Name for this example if we want to call the name in Enumeration List. 

Nullable Data Type(nullable):

Apart from enum, what if I say you can provide null value to a field? Yes nullable provides us such facility to assign null value to a field. It is derived from System.Nullable<T> struct. We can write a nullable of Int32 as Nullable<Int32> which means the Int value may contain null. In these nullable types, we can add add normal values as well as null values. You may ask what is the need of assigning null value to a field? SO, my friend the answer is that we can assign null to Boolean and numeric values. And this is very helpful while we are dealing with the database or other datatypes that may not be assigned some value. For example, a Boolean field in your database may be true or false, or it may be undefined. The syntax for nullable data type is:

  1. <data_type> ? <variable_name> = null;  
  2.   
  3. Example:  
  4.   
  5. int ? roll = null;  
  6.   
  7. int ? age = 45;    

Null Coalescing Operator(??):

This operator is used with nullable types only. This operator helps in assigning a value other than null to a field. If the first value assigned to the field is null, it will return the second value which is not null, otherwise it will return the first value assigned. The syntax is:

  1. <variable_name> = value1 ?? value2  

 

Example:

  1. int ? d = null;  
  2.   
  3. int ? a = 23;  
  4.   
  5. int age;  
  6.   
  7. age = d ?? 24;  
  8.   
  9. Console.WriteLine(“age”);  
  10.   
  11. age= a?? 45;  

Here the results will be:

24

23

As d is null in first case, it will result the second value 24. And in second case a is having value 23 so, it will return 23, not the second value 45.

I hope this article has helped you.

Please do share, comment and send feedback.

(As your contributions have always helped me in growing my own as well as my readers' knowledge.)