How Do You Identify Nullable Type in C# (C Sharp)Can you assign null to an integer variable? Not in other languages. But you can do it in C# using nullable types. Not just integer, any value types can accept null value if it is declared as nullable type. When you declare it as nullable, in addition to the range of values that your value type can accept it also accepts null value. Consider the following example:
class sampleClass
{ Output of this code will be: Value of intVar is null You declare the integer variable intVar as nullable type by associating ? symbol after value type but before the variable name. The corresponding code is highlighted in bold in the example shown above. How to Identify Nullable Type? When you browse through the code, you can identify nullable type by looking at the ? symbol. What if you have to identify nullable type during execution of your code to decide on further processing? Here are the ways: Use
typeof operator Identify Nullable Type Using typeof Operator: To know how you can identify nullable type using typeof operator, browse through the code sample given below: class sampleClass
{/ Output of
this code will be: In this example you have a nullable type variable called intVar. You first fetch the type of intVar using typeof operatogr and assign it to a System.Type variable called typeOfVar. You then check if the type retrieved is a generic type. If so, you check if it is nullable by checking its definition against: typeof(Nullable<>)
Identify Nullable Type Using System.Reflection Namespace: Assume that you have an internal class called employee containing certain attributes. You have to display its attributes which are of nullable type. How will you do it? You can do it using the methods of System.Reflection namespace. Here is the code sample for it: internal
class employee { How Not to Identify Nullable Type? In addition to understanding above mentioned ways of identifying nullable type, you should also be aware of the following ways which will not help you in identifying nullable type but still they might mislead you: Using
GetType method of System.Type Both these ways are used to identify the type of the variable, but they will not predict if your variable is nullable. To make it clear, consider the following example: class sampleClass
{ Type of intVar is System.Int32 You get such an output because GetType() method determines only the value type associated with a particular variable. It cannot identify if the variable is nullable or not. Similarly using is operator will also check for the value type associated with the variable. And it doesnt bother about the nullable nature of the variable. Given below is an example of is operator: class sampleClass
{ Output of this code will be: intVar is an integer variable Hence always remember that GetType() method as well as is operator will not identify nullable type. They identify only the associated value type.
|