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

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

    You can't cast a null to an int, as an int is a value type. You can cast it to an int? though.

    What is it you want to achieve?

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

    A method of a generic class that returns nothing works:

     Class GetNull(Of T)
          Public Shared Function Value() As T
               Return Nothing
          End Function
     End Class
    
    
    
     Debug.Print(GetNull(Of Integer).Value())
    
    0 讨论(0)
  • 2021-02-13 15:05

    Use null-coalescing operator or ??

    Example:

    int? a = null;
    return a ?? 0; //this will return 0
    

    It's a new feature in C#. It returns the left-hand operand if the operand is not null; otherwise, it returns the right-hand operand.

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

    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"]);
    
    0 讨论(0)
  • 2021-02-13 15:09

    Check out this post for a mostly complete method for writing an extension to do just this. My scenario is pulling data from a NameValueCollection.

    http://hunterconcepts.com/blog/Extensions_HttpRequestFormQueryString/

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

    You'll need a return type of Nullable(Of Integer).

    0 讨论(0)
提交回复
热议问题