tags:

views:

80

answers:

1

i am trying to write a function that will make DataRow[column] return nullable typed data. for example: if i have a property

int? iValue { get; set; }

and the DataRow["ID"] will have the int ID in the Database i want to make a wrapper function that will check if the value of the DataRow["ID"] is DBnull and set the iValue to null. and so on for the rest of the datatypes. i wrote the following function

public static void CDB<T>(ref T tData, object objDBDataItem)
{
    if (objDBDataItem.GetType().FullName == "System.DBNull")
     tData = default(T);
    tData = (T)objDBDataItem;
}

to call the function i do the following

CDB(ref iValue , DataRow["ID"]);

this should initialize the value of iValue to the integer value of DataRow["ID"] or null if the value in the DB is null. the problem is that this code dont work because i am not allowed to pass proprities as reference. but the idea is that i dont want to call the function as

iValue = CDB<int>(DataRow["ID"]);

so far i was able to make the function work if i change it to be called in the format of

iValue = CDB(iValue, DataRow["ID"]);

but i dont like the idea that i need to repeat iValue (one time to get the Type and one time so that i assign the return value to it.

any suggesions?

+1  A: 

One option is to pass a delegate into your function:

public static void CDB<T>(object objDBDataItem, Action<T> setter)
{
    T data;
    if (objDBDataItem is System.DBNull)
        tData = default(T);
    else
        tData = (T)objDBDataItem;

    setter(data);
}

And call it like this:

CDB(DataRow["ID"], (int? i) => iValue = i);

It's also worth pointing out that the logic you describe to hide DBNull is already provided by System.Data.DataRowExtensions.Field:

iValue = DataRow.Field<int?>("ID");

Out of curiosity, why don't you like assigning iValue this way?

dahlbyk
well i want the function to be as simple as possible. i already know that the type of the iValue is int? so i dont want to repeat myself by typing it again. i mean it will be time consuming to write the type of each property while writing the code. and the compiler should figure it out by its own from the type of iValue.thanks for the delegate function but i think its more complex then the other solutions :(. anyway i think i will go for [iValue = CDB(iValue, DataRow["ID"]);] which is bad for repeating the iValue twice but i think this is the best solution for donkey copy paste :)
Karim