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.
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
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With