Search code examples
c#.netcasting

I want "(int)null" to return me 0


How can i get 0 as integer value from (int)null.

EDIT 1: I want to create a function that will return me default values for null representation in their respective datatypes.

EDIT 2: How can i work in this scenario for using default.

(int)Value

Where Value can be null or any integer value. I dont know datatype of value at run time. But i will assure that Value should either contain null or Integer value only.


Solution

  • You can use the Nullable structure

    int value = new Nullable<int>().GetValueOrDefault();
    

    You can also use the default keyword

    int value = default(int);
    

    Following 2nd edit:

    You need a function that receive any type of parameter, so object will be used. Your function is similar to the Field<T> extension method on a DataRow

    public static T GetValue<T>(object value)
    {
        if (value == null || value == DBNull.Value)
            return default(T);
        else
            return (T)value;
    }
    

    Using that function, if you want an int (and you expect value to be an int) you call it like:

    int result = GetValue<int>(dataRow["Somefield"]);