I want “(int)null” to return me 0

前端 未结 8 2245
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 14:14

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 representa

8条回答
  •  独厮守ぢ
    2021-02-13 15:08

    You can use the Nullable structure

    int value = new Nullable().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 extension method on a DataRow

    public static T GetValue(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(dataRow["Somefield"]);
    

提交回复
热议问题