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

前端 未结 8 2239
隐瞒了意图╮
隐瞒了意图╮ 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:13

    A generic method that returns a cast instance of an object or the default value could be implemented as follows:

    static T Cast<T>(object value) {
        if (value is T)
            return (T)value;
        else
            return default(T);
    }
    

    This way, using a valid value will yield the value itself:

    int value = Cast<int>(4); //value = 4
    

    and a null value will get the default:

    int value = Cast<int>(null); //value = 0
    

    Notice that since the method takes object as an argument, this will cause boxing when used with struct objects (like int).

    0 讨论(0)
  • 2021-02-13 15:14

    You can use the default keyword to get the default value of any data type:

    int x = default(int);        //  == 0
    string y = default(string);  //  == null
    // etc.
    

    This works with generic parameters as well:

    Bar<T> Foo<T>() {
        return new Bar<T>(default(T));
    }
    

    In case you have a variable of type object that may contain null or a value of type int, you can use nullable types and the ?? operator to convert it safely to an integer:

    int a = 42;
    object z = a;
    int b = (int?)z ?? 0;        //  == 42
    int c = (int?)null ?? 0;     //  == 0
    
    0 讨论(0)
提交回复
热议问题