Ok, I’ve been hacking around this particular problem for a month now, but think I’ve got a bead on how to stop it. So, I hope this helps someone!
The Situation
I’ve got a TableAdapter in C# and I’m using a Query to return a scalar value that ultimately becomes a double data type. The trouble is that if the query returns a NULL, I get the error:
‘NullReferenceException was unhandled by user code’
Here’s the code that gives me the error:
myTableAdapters.myTableAdapter ta = new myTableAdapters.myTableAdapter(); double median = (double)ta.GetMedianLineItems();
When I hit a null, it crashes.
The Solution
What I want to happen is to ‘continue’ in my loop if I get a null. In my case, and the code I’ll show below, it’s acceptable to continue if I get ‘0’. Here’s the code that works in my case:
myTableAdapters.myTableAdapter ta = new myTableAdapters.myTableAdapter(); double median = Convert.ToDouble(ta.GetMedianLineItems()); if (median == 0) { return; }
Using the ‘System.Convert’ object prevents the crash. Convert gives you a long list of data types you can attempt to convert to: dates, decimals, doubles, int’s, booleans, strings, chars, etc, etc.
A really handy method of Convert is IsDBNull, which will let you check a value in a datatable before you try to assign it to a variable and get a null error.
Nulls, for being a whole lot of nothing, can be a real PITA.
Cheers,
Byron
this is good info, however here is something interesting as well.
I have found several functions on the web that I have combined into two generic helper functions to use. I have put them into a helper class that I include with in all of my current projects, I have several helper files based on what functionality I need which compile into a single class (hence the partial class definition) like I have file that deals with different helper function for working with Enums and a class that holds a business logic functions, but at the end I can call any of them like Helper.FunctionName() as needed.
Now back to the issue at hand:
the code above is good but it is very specific need to be repeated anywhere you need this validation. my approach is that I have a universal function that I pass an object to and the type I expect back and it validates and convert as needed, returning either the proper value back or a default value for the specific type.
the only issue is that I kind of have to convert any value I am passing in, to string but so far I had no problem with this approach.
so for this example I would use call like this :
var aa = Helper.GetValidatedValue(ta.GetMedianLineItems())
public static partial class Helper
{
///
/// This function will try to convert a string value provided as a parameter into
/// specific type that is indicated by type reference “T”
/// if value can not be converted into desired type, a default value for that type is returned
/// usage : var exampleVariable = GetValidatedValue(“14”)
/// value of the exampleVariable will be “14” if conversion is ok
/// and “0” if value can not be converted into “int”
///
///
///
///
public static T GetValidatedValue(object param)
{
return TryParse(param);
}
private static T TryParse(object inValue)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
try
{
return (T)converter.ConvertFromString(inValue.ToString());
}
catch
{
return default(T);
}
}
}
THIS IS A CORRECTION TO POST ABOVE!
for some reason all of my function calls in original post have been changed to drop the ” Less then ” T ” Greater Then ” designation, hopefully this will clear things up
var aa = Helper.GetValidatedValue”<>”(ta.GetMedianLineItems())
public static T GetValidatedValue<>(object param)
{
return TryParse<>(param);
}
private static T TryParse<>(object inValue)
{
var converter = TypeDescriptor.GetConverter(typeof(T));
try
{
return (T)converter.ConvertFromString(inValue.ToString());
}
catch
{
return default(T);
}
}
Hi Vlad,
Thanks for the tip! I can definitely see how it would be attractive to have a universal function to deal with the Null situations for any data type.
Either approach should work fine. Just depends on which you are more comfortable with.
Best regards,
Byron
thanks Byron,
I thought that I just post this here so if someone is searching for this info they would have it in one place 🙂