Richard Gale
Richard Gale

Reputation: 1952

Single Function Call to return any possible data type

Is it possible to create a function which I can call, passing an object and have that function return any data type.(I'm guessing I have to tell it the datatype to return, so below I have just passed a string for this - there may be a cleaner way to deal with this)

public x GetValue(Object value, string datatype)

Could I call this passing: (DataRow["OrderID"], "Integer")

Then call it again by passing: (DataRow["CustomerName"], "String") ?

Hope this makes sense.

Upvotes: 0

Views: 119

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156978

Yes, it is called generics:

public T GetValue<T>(Object value)
{
    if (value == DbNull.Value)
    {
        return default(T);
    }

    return (T)value;
}

Then call it like this:

string s = GetValue<string>(DataRow["CustomerName"]);

Or, as Tim Schmelter suggested, in this case you could use:

DataRow.Field<string>("CustomerName");

Upvotes: 5

Related Questions