Posts
208
Comments
1144
Trackbacks
51
Parse Nullable Types

Often when working with a textbox or some other control, it is necessary to call the Parse() method to do a conversion for our business object property.  For example, consider a web form where you are assigning:

person.DateOfBirth = DateTime.Parse(txtDateOfBirth.Text);

This is all well and good if your field is required and you've already got a UI validation ensuring that the user typed a date into the text box.  But what do you do if the field is not required and you'd like to use Nullable for your DateOfBirth property.  Rather than littering your code with a bunch of if/then statements or creating methods to do it, the best bet is to create a re-usable class that can do this for you so that you're syntax can look like this:

person.DateOfBirth = NullableParser.ParseNullableDateTime(txtDateOfBirth.Text);

NullableParser is a static class (a new feature of C# 2.0) that has a ParseXXX() method for each value type.  To implement this internally, our method could simply look like this:

public static DateTime? ParseNullableDateTime(string s)

{

  if (string.IsNullOrEmpty(s))

  {

    return null;

  }

  else

  {

    return DateTime.Parse(s);

  }

}

 

The problem with this is that I have to write a repetitive IF statement for every single method in my static class - the only thing that would be different would be the return DateTime.Parse(s);  line.  In order to solve this issue by making the code more concise, we can leverage a delegate with delegate inference (another new C# 2.0 language features) within a generic method (generic method being another C# 2.0 new language feature).  First, we might define our delegate:

private delegate T ParseDelegate(string s);

Next we define the generic method passing the appropriate delegate:

private static Nullable<T> ParseNullable<T>(string s, ParseDelegate<T> parse) where T : struct

{

  if (string.IsNullOrEmpty(s))

  {

    return null;

  }

  else

  {

    return parse(s);

  }

}

With this simple generic method defined, the rest of the class is trivial as now all of the ParseXXX() methods can be rewritten like this (utilizing the appropriate Parse() method for delegate inference):

public static int? ParseNullableInt(string s)

{

  return ParseNullable<int>(s, int.Parse);

}

Leveraging the new features of C# 2.0 (i.e., nullable types, delegate inference, and generics) can result in code that is more efficient, concise, and easier to maintain.

posted on Monday, January 16, 2006 6:20 AM Print
Comments
Gravatar
# re: Parse Nullable Types
Hans
4/27/2006 6:00 AM
I have tried to implement this! Cant get it to work. I get the following error: "Constraints are not allowed on non-generic declarations". Could you please show the full example code? I mean the full code together!

Regards Hans
Gravatar
# re: Parse Nullable Types
Hans
4/27/2006 7:11 AM
This is how I've implemented it, what am I doing wrong:

using System;

namespace MyNamespace
{

public static class NullableParser
{
private delegate T ParseDelegate(string s);

public static int? ParseNullableInt(string s)
{
return ParseNullable<int>(s, int.Parse);
}

public static DateTime? ParseNullableDateTime(string s)
{
return ParseNullable<DateTime>(s, DateTime.Parse);
}

private static Nullable ParseNullable(string s, ParseDelegate parse) where T : struct
{
if (string.IsNullOrEmpty(s))
{
return null;
}
else
{
return parse(s);
}
}

}

}
Gravatar
# re: Parse Nullable Types
Steve
4/27/2006 7:48 AM
You need to change your delegate from:
private delegate T ParseDelegate(string s);

to this:
private delegate T ParseDelegate<T>(string s);

If you want to give me your email then I'll be happy to email you the complete code for the class.
Gravatar
# re: Parse Nullable Types
Steve
4/27/2006 7:51 AM
Also, you're post just made me realize that I didn't accurately post the code in my original post to reflect my code (I'll change this now).

This method:
private static Nullable ParseNullable(string s, ParseDelegate parse) where T : struct

should have this signatue:
private static Nullable<T> ParseNullable<T>(string s, ParseDelegate<T> parse) where T : struct
Gravatar
# re: Parse Nullable Types
Hans
4/27/2006 7:59 AM
My email:
finnhasse67@hotmail.com

Thank you very much for your help!

Regards Hans (Sweden)
Gravatar
# re: Parse Nullable Types
Hans
4/27/2006 8:07 AM
Thank you very much! Now it's working!

/Hans
Gravatar
# re: Parse Nullable Types
Li
5/18/2006 12:07 PM
If you assign a null value to a textbox, does it stay that way after a postback if no changes are made?
Ex (in Page_Load):
if(!this.IsPostback)
{
mytextbox.Text = null;
}
else if(mytextbox.Text == null)
{
mylabel.Text = “stayed null”;
}
else
{
mylabel.Text = “changed to something else”;
}
Gravatar
# re: Parse Nullable Types
Alan Hemmings
5/25/2006 2:25 PM
// conditional operator shines through!
public static DateTime? Parse(string s)
{
return String.IsNullOrEmpty ? null : DateTime.Parse(s);
}
Gravatar
# re: Parse Nullable Types
Alan Hemmings
5/25/2006 3:07 PM
// Just realised my previous post is faulty.
// here is the fix.

public static DateTime? ParseSS(string s)
{
return string.IsNullOrEmpty(s) ? null : new DateTime?(DateTime.Parse(s));
}
Gravatar
# re: Parse Nullable Types
Ajoy Majumdar
4/23/2008 3:35 AM
Hi,
I was try to implement this code, it get compilation error. I get the following error: "Constraints are not allowed on non-generic declarations".

So can you send full error free code in my email id?

Thanks.
Gravatar
# re: Parse Nullable Types
Abe Park
9/17/2009 5:55 AM
Can you please send the full code as well?
It would have been great if this feature was built into C#.

Thank you.
Gravatar
# re: Parse Nullable Types
urkurk
12/29/2009 4:11 AM
cool shit
Gravatar
# re: Parse Nullable Types
urkurk
12/29/2009 4:37 AM
hi i modified your code so i won't have to pass the delegate variable
anyways, thanks for your code sample

public static Nullable<T> ParseNullable<T>(string s) where T : struct
{

if (string.IsNullOrEmpty(s))
{

return null;

}

else
{

T? retval = null;

if (typeof(T)==typeof(System.Int32))
{
int result;
if (int.TryParse(s, out result))
{
retval = (T)Convert.ChangeType(result, typeof(T));
}

}
else if (typeof(T) == typeof(System.DateTime))
{
DateTime result;
if (DateTime.TryParse(s, out result))
{
retval = (T)Convert.ChangeType(result, typeof(T));
}

}


return retval;


}

}
Gravatar
# re: Parse Nullable Types
Starbuck
4/3/2012 11:30 AM
I stumbled on this blog and will offer a more modern approach with an extension method:
public static DateTime? AsNullableDate(this string date)
{
if (String.IsNullOrEmpty(date))
return null;
return DateTime.Parse(date);
}

Post Comment

Title *
Name *
Email
Comment *  
Verification

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud