Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Handling DB Nulls
Message
De
28/12/2009 13:36:57
 
 
À
28/12/2009 12:05:10
Information générale
Forum:
ASP.NET
Catégorie:
Conception classe
Divers
Thread ID:
01440804
Message ID:
01440890
Vues:
41
Yes, lots of people have now suggested Extension methods and that is probably a better idea than my old worn-out static methods (this was written in the pre-2.0 days). I should probably update it a bit.

But, probably not quite the way you've suggested Gregory. The intent of my original class and methods was to work with objects, specifically data in the DataRows of a DataTable (hence my checking for DBNull.Value, which you didn't do in your example).

Here's a quick start of how I might change it:
public static class BBExtensions
{
	public static DateTime GetNonNull(this object Test, DateTime Default)
	{
		if (Test != null && Test != DBNull.Value)
		{
			DateTime TestDT = Convert.ToDateTime(Test);
			DateTime SqlNull = new DateTime(1900, 1, 1);
			DateTime NetNull = new DateTime(1, 1, 1);
			if (TestDT != SqlNull && TestDT != NetNull)
				return TestDT;
			else
				return Default;
		}
		else
			return Default;
	}
	public static int GetNonNull(this object Test, int Default)
	{
		if (Test != null && Test != DBNull.Value)
			return Convert.ToInt32(Test);
		else
			return Default;
	}
}
~~Bonnie



>>Kevin,
>>
>>I'm sure I've posted my GetNonNull set of static methods here a gazillion times. <g> Here it is again in the form of a link to my blog post about it:
>>
>>http://geek-goddess-bonnie.blogspot.com/2009/11/getting-non-null-data.html
>>
>>~~Bonnie
>>
>
>Bonnie,
>
>Is it fair to say that all types - except string - will be value types ?
>
>If so - consider this for the next update of the blog
>
>
>	public static class ExtensionMethods
>	{
>		//______________________________________________________________________
>		public static T GetNonNull<T>(this  T? value) where T : struct
>		{
>			return value == null ? default(T) : (T)value;
>		}
>		//______________________________________________________________________
>		public static string GetNonNull(this string value)
>		{
>			return value == null ? "" : value;
>		}
>		//______________________________________________________________________
>	}
>
>
>// test
>public class test2
>	{
>		
>
>		//______________________________________________________________________
>		public static void Main( string[] args )
>		{
>			int? i = null;
>			bool? b = null;
>			string x = null;
>			DateTime? dt = null;
>
>			Console.WriteLine("i: {0}", i.GetNonNull());
>			Console.WriteLine("b: {0}", b.GetNonNull());
>			Console.WriteLine("x: {0}", x.GetNonNull());
>			Console.WriteLine("dt: {0}", dt.GetNonNull());
>
>			Console.ReadLine();
>		}
>	}
>
>
Bonnie Berent DeWitt
NET/C# MVP since 2003

http://geek-goddess-bonnie.blogspot.com
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform