65.9K
CodeProject is changing. Read more.
Home

Set Value Types to Null

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.62/5 (9 votes)

Nov 15, 2006

viewsIcon

30899

downloadIcon

91

How to assign Null to Value Types

Introduction

I created this article to show developers that are moving to .Net 2.0 that you can now set value type fields to null. This feature was introduced in .Net 2.0. 

Here is a list of some of the Value Types in .Net.

Structs
Enumerations
Integral types
Floating-point types
decimal
bool
user defined structs

Example

static void Main(string[] args)

{

bool? mynullBool = null;

int? mynullInt = null;

// Note that mynullBool will be set to null

Console.WriteLine("mynullBool={0}", mynullBool);

// Note that mynullInt will be set to null

Console.WriteLine("mynullInt={0}", mynullInt);

// How to Assign default values for null values

mynullBool = GetBool() ?? true;

mynullInt = GetInt() ?? 2006;

// Note that mynullBool will be set to true

Console.WriteLine("mynullBool={0}", mynullBool);

// Note that mynullInt will be set to 2006

Console.WriteLine("mynullInt={0}", mynullInt);

}

 

static bool? GetBool()

{

return null;

}

 

static int? GetInt()

{

return null;

}

Conclusion

The following link points to MSDN for value types. http://msdn2.microsoft.com/en-gb/library/s1ax56ch.aspx

The following link points to MSDN for nullable types. http://msdn2.microsoft.com/en-us/library/1t3y8s4s.aspx

About BuddyWork

Developed Enterprise Applications for various sectors in C, C++, C#, VB, VB.NET, Clipper, Artemis and many more languages. 

Currently working in London as a .Net Architect. 

Microsoft qualification consists of MCSD.Net and MCPD (Enterprise)