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
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?
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())
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.
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"]);
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/
You'll need a return type of Nullable(Of Integer)
.