Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

casting

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.

like image 721
Shantanu Gupta Avatar asked Jan 19 '10 19:01

Shantanu Gupta


2 Answers

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
like image 75
dtb Avatar answered Oct 16 '22 11:10

dtb


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"]);
like image 27
Pierre-Alain Vigeant Avatar answered Oct 16 '22 10:10

Pierre-Alain Vigeant