Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Exploring Nullable types: Part 1

, 17 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
In this post, I am going to talk about Nullable types.

In this post, I am going to talk about Nullable types. Actually most of developers know, in C#, we have mainly two types:

  1. Reference type
  2. Value type

But we have one more type that is called Nullable type.

Actually, it is a value type but it has feature of both reference and Value type.

As we know, a value type is allocated space on stack, and every value of type must be initialized to some value during declaration. If you don’t provide by yourself, C# does it for you. So every value type is assigned some value whether you initialize it or not.

Nullable type has a capability to hold a value or can have null reference, means there is no value. Nullable types were introduced in .NET 2.0.

We can declare and initialize a Nullable type as:

//This is a Nullable of Int type
Nullable<int> t = 5;

C# also provides a short hand syntax for this as:

int? i = 5;

If you would not assign a value, you can do it with Nullable types as we can do it with reference types.

Now let’s see it in the reflector how it got implemented. Here you can see the Class declaration as:

Nullable

public struct Nullable<T> where T: struct

It means Nullable can be used over struct type, i.e., value type.

Here we will see some of the main properties of Nullable type and leave default ones. Now let's go to the details of method public Nullable(T value). This is parameterised constructor. Now let's see what is inside this code:

Here you can see that this is assigning value to the variable and setting hasValue as true.
So it actually has one property hasValue that does the entire job. By default, it is set to false and once we assign some value in it, it is set as true. So whenever one accesses it without assigning it a value, it returns null reference.

Now let's see the HasValue property.

It is just returning the hasValue.
Now let's see public T Value { get; } what it does:

As you can see whether hasValue is true or not. If false, throw some exception else it returns the value.

Also let's have a view at two more next methods public T GetValueOrDefault() and public T GetValueOrDefault(T defaultValue). As the method name suggests, that returns the existing value and if it is not set then return the type’s defult value. The definition is like this:

So you can see that it checks the hasValue and based on this, returns the result. Similarly if you want to see public override bool Equals(object other) method, it has the code like:

This also checks the hasValue before comparing it.

There are two operator’s method you can see at last. You all must be knowing this is Operator Overloading. But what is this for? Let's see the code below:

int i = 5;
//Assigning a int type to a Nullable of int
Nullable<int> t = i;

Actually, here I have declared and intialised an int variable and created a nullable type and assigned the int variable to it. This is actually accomplished with the help of the operators.

So it means we can assign a value type to a Nullable type whose underlying type is the same as the underlying type of a Nullable type without any casting.

But vice versa is not possible. You have to do explicit cast as:

Nullable<int> t = 5;
//Need an explicit cast
int i = (int)t;

But you always write as:

Nullable<int> t = 5;
// No need for a cast because t.Value is actually the 
// underlying type and holds the value
int i = t.Value;

So I think you all must have enjoyed. There are a lot more things still remaining which I’ll cover in my next post.
Cheers,
Brij


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brij
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.
 
He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.
 
He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.
 
He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.
 
Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Brij's arena of .NET
 
Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 2 PinmemberCollin Jasnoch17-Oct-11 6:33 
GeneralRe: My vote of 2 PinmvpBrij14-Nov-11 10:09 
GeneralRe: My vote of 2 PinmemberCollin Jasnoch14-Nov-11 10:31 
GeneralRe: My vote of 2 [modified] PinmvpBrij14-Nov-11 20:18 
GeneralRe: My vote of 2 PinmemberCollin Jasnoch15-Nov-11 4:52 
Brij wrote:
You must have noticed that this is a blog post. It is neither an article nor a
Tip/trick. I wrote it for my blog and CodeProject takes the feed from there.


 
Actually I had not noticed. My appologies for that.
 

Brij wrote:
The intent of this post is to highlight Nullable type. Now why highlight?
because I have seen lot of developers don't use it ( It might not true in your
area) and write some custom code for this.

 
Yeah, I have not run into any programmers (of C#) that do not know about nullables. Basically if you have not begun using generics you are living in the dark ages of programming Poke tongue | ;-P
 

 
OK, so you asked for some info on what you could add. Well here are some sugestions.
 
Explain why it is important. There can be numerous reasons or angles for this. I think the simpliest reason is as follows:
 
Structure variables such as System.Int32 have a default value, and in the int case it is 0. If you are building a system and Require your user to enter something using a standard int could cause problems because external compontents (maybe a validator or something) will not know if the user entered '0' or if that is simply the default. By using Nullable<int> it is easily understood if a value has been entered, as it is no longer null.
There are many other examples I am sure you can come up with.
 
Currently as your post stands, you explain what it is but it seems if someone did not know about it they would disreguard using it because it simply adds complexity. For why they will ask. Provide some of those examples and I will adjust my vote.
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 17 Oct 2011
Article Copyright 2011 by Brij
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid