(LocalVariable)ABC.string(Name)= (Idatareader)datareader.GetString(0);
this name value is coming from database.. what happening here is if this name value is null while reading it's throwing an exception?
I am manually doing some if condition here. I don't want to write a manual condition to check all my variables..
I am doing something like this now..
string abc = (Idatareader)datareader.GetValue(0);
if(abc = null)
//assiging null
else
assiging abc value
is there something like can we write extension method for this? thanks
My solution is that:
When,
Status = GetValue<string>(currentDataRow["status"])
Combining top solutions and suggestions, here is a C# 6 arrow expression version with support for
GetValue<T>
andGetValueOrDefault<T>
with optional default value parameters.Similar to @sky-sanders answer but less strict with conversions:
I'd use something like this:
Here is a couple extension methods that will nicely wrap up all of your concerns around retrieving strongly typed values from a data reader. If the value is DbNull the default of the type will be returned. In the case of
string
which is a class, anull
will be returned. If the field wasint
, then0
would be returned. Additionally, if you are expecting anint?
, say from an nullable int field,null
would be returned.Specific Usage for Kumar's case:
General Usage
or
or
Extension
from http://skysanders.net/subtext/archive/2010/03/02/generic-nullsafe-idatarecord-field-getter.aspx