Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign Null value to Non-Nullable type variable in C#?

Tags:

c#

Such as i have declared,

double x;

now i want to assign

x=NULL how can i do this ? I have seen some other answers of it but couldn't understand them, that's why opening this thread .

like image 778
MSU Avatar asked Mar 19 '13 05:03

MSU


3 Answers

You have to declare it as a nullable type:

double? x;
x = null;

Non nullable types like double can not be null

like image 93
TGH Avatar answered Nov 19 '22 08:11

TGH


You cant assign null to a non-nullable type

You can use NaN (not a number) for a non-nullable double

double x;
x = double.NaN;
like image 26
sa_ddam213 Avatar answered Nov 19 '22 08:11

sa_ddam213


Nullable types are instances of the System.Nullable(Of T) struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

double? amount = null;

http://msdn.microsoft.com/en-us/library/vstudio/2cf62fcy.aspx

Possible Duplicates:

Why can't I set a nullable int to null in a ternary if statement?
Nullable types and the ternary operator: why is `? 10 : null` forbidden?

like image 37
internals-in Avatar answered Nov 19 '22 09:11

internals-in