Steve Michelotti

A .NET Developer's Toolbox

  Home  |   Contact  |   Syndication    |   Login
  175 Posts | 0 Stories | 940 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn

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




Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Code

Publications

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Monday, January 16, 2006 6:20 AM

Feedback

# re: Parse Nullable Types 4/27/2006 6:00 AM Hans
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

# re: Parse Nullable Types 4/27/2006 7:11 AM Hans
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);
}
}

}

}

# re: Parse Nullable Types 4/27/2006 7:48 AM Steve
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.

# re: Parse Nullable Types 4/27/2006 7:51 AM Steve
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

# re: Parse Nullable Types 4/27/2006 7:59 AM Hans
My email:
finnhasse67@hotmail.com

Thank you very much for your help!

Regards Hans (Sweden)

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

/Hans

# re: Parse Nullable Types 5/18/2006 12:07 PM Li
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”;
}

# re: Parse Nullable Types 5/25/2006 2:25 PM Alan Hemmings
// conditional operator shines through!
public static DateTime? Parse(string s)
{
return String.IsNullOrEmpty ? null : DateTime.Parse(s);
}

# re: Parse Nullable Types 5/25/2006 3:07 PM Alan Hemmings
// 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));
}


# re: Parse Nullable Types 4/23/2008 3:35 AM Ajoy Majumdar
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.

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

Thank you.

# re: Parse Nullable Types 12/29/2009 4:11 AM urkurk
cool shit

# re: Parse Nullable Types 12/29/2009 4:37 AM urkurk
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;


}

}

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: