Fremus.co.za

Demistifying Life and Web Development

Using nullable types in C#

I was busy reading an MSDN article on modifying an attribute’s value in an XML document and I read the bit that looks like this:

int? c2 = (int?)root.Attribute("Att2");
Console.WriteLine("c2:{0}", c2 == null ? "attribute does not exist" : c2.ToString());

Notice the ternary operator after the the type. It’s saying that c2 can be null. If you wrote code like this:


//declare variable
int c = null;

You will get a compiler error. Also notice the conditional shorthand, which is something I see a lot in JavaScript. If I wrote this:


string myName = "Frederik";

Console.WriteLine("myName:{0}", myName == "Fredrik" ? myName : "My name is not correct");

The result will read “My name is not correct”.

  • Share/Bookmark
posted by fr3dr1k in C# and have No Comments
Tags:

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Get Adobe Flash playerPlugin by wpburn.com wordpress themes