Blog
Archive
<July 2014>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789
Monthly
Go
Search
  |  

Fun with the ternary operator ?, Nullable types and object initializers

Jan 5

Written by:
1/5/2011 11:48 AM  RssIcon

lets start with a simple class for demonstration purposes – note, that the DateOfBirth is nullable …

   1: public class Person
   2: {
   3:     public string Name { get; set; }
   4:     public DateTime? DateOfBirth { get; set; }
   5: }

 

using object initializers, we can instantiate the class in the following way:

   1: // works
   2: Person p1 = new Person() { Name="Michi", DateOfBirth=DateTime.Now };

 

but what happens, if we want to do the initialize the values based on some condition? you could be tempted to write the following code:

   1: // doesnt compile
   2: // Type of conditional expression cannot be determined because there is no implicit conversion between ''
   3: bool someCondition = false;
   4: Person p2 = new Person()
   5: {
   6:     Name = "Michi",
   7:     DateOfBirth = (someCondition == true ? null : DateTime.Now)
   8: };

 

boom! you get a compile error:

compile_error

 

interestingly enough, an assignment from null to DateTime? is working!

   1: // but this works...
   2: Person p3 = new Person();
   3: p3.Name = "Michi";
   4: if(someCondition == true)
   5:     p3.DateOfBirth = null;
   6: else
   7:     p3.DateOfBirth = DateTime.Now;

 

hmmm… so how do we get to use object initializers for elegante syntax but still are able to assign nullable types? fallback to the “real” type

that is used behind the scenes if you declare a DateTime? – it’s an instance of the System.Nullable struct – see Nullable Types C# on MSDN.

 

so here is the working code:

   1: // in order to still use object intializers you can use the "real" type of DateTime?
   2: Person p4 = new Person()
   3: {
   4:     Name = "Michi",
   5:     DateOfBirth = (someCondition == true ? new Nullable() : DateTime.Now)
   6: };

Tags:
Categories:
Location: Blogs Parent Separator Michael Seirer

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel