Tracing Nullable type in C#


During industrial internship at Lovely Infotech(Aug 2013 – Dec 2013), one of my friend has problem in a program. He want to fetch some data from database and which give null in some cases, to store in value type variable(actually in database, there is field that may accept null value, in case of when data save to database it allow null to save, so obviously when returning this value it will return null).  And C# doesn’t allow to take null in value type variable, because C# datatype have a fixed range and are represented as a type in the System namespace. So after give many try on this error, he reached at conclusion that C# value type doesn’t contain null value.

Note #1: Value types can never be assigned the value of null.

So C# provide a way to a variable that is value type can have value or null; A nullable data type can represent all values of its type plus null. The question mark (?) symbol is appended to datatype, for defining nullable type;

Note #2: Nullable type cannot create on reference type.

for e.g.

Note #3: In C#, the ? suffix notation is a shorthand for creating an instance of the generic System.Nullable <T> structure type.

Working with Nullable Types

As stated in example nullable data types useful when working with databases. For example, assume the following class DataFetcher that give the total number of processed row.

Now assume the following Main() method:

In this Main() class, member of DataFetcher in invoked and finding the value using HasValue and Value member.


One thought on “Tracing Nullable type in C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s