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:
- enum < enum_name >
-
- {
-
- Enumeration list;
-
- };
-
- Example:
-
- enum MyData
-
- {
- Name,
- Address,
- DOB,
- Education
- };
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:
- <data_type> ? <variable_name> = null;
-
- Example:
-
- int ? roll = null;
-
- 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:
- <variable_name> = value1 ?? value2
Example:
- int ? d = null;
-
- int ? a = 23;
-
- int age;
-
- age = d ?? 24;
-
- Console.WriteLine(“age”);
-
- 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.)