Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set null value to int in c#?

int value=0;  if (value == 0) {     value = null; } 

How can I set value to null above?

Any help will be appreciated.

like image 265
user2902180 Avatar asked Oct 22 '13 15:10

user2902180


People also ask

Can you assign null to an int in C?

In c, besides pointers you cannot set c objects to NULL. You cannot cast NULL to other object since it encapsulates nothing. So you might want to set your struct variables to 0 instead of NULL.

How do you assign a null to an integer?

Integer int = null; int is a reserved keyword; this isn't valid Java syntax. Besides, the OP isn't referring to primitives.

Can we store null in int?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

Can you assign a variable to null in C?

In C programming language a Null pointer is a pointer which is a variable with the value assigned as zero or having an address pointing to nothing. So we use keyword NULL to assign a variable to be a null pointer in C it is predefined macro.


2 Answers

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:

int? value = 0;  if (value == 0) {     value = null; } 

Further Reading

  • Nullable Types (C# Programming Guide)
like image 146
p.s.w.g Avatar answered Sep 21 '22 17:09

p.s.w.g


Additionally, you cannot use "null" as a value in a conditional assignment. e.g...

bool testvalue = false; int? myint = (testvalue == true) ? 1234 : null; 

FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

So, you have to cast the null as well... This works:

int? myint = (testvalue == true) ? 1234 : (int?)null; 

UPDATE (Oct 2021):

As of C# 9.0 you can use "Target-Typed" conditional expresssions, and the example will now work as c# 9 can pre-determine the result type by evaluating the expression at compile-time.

like image 28
doublehelix Avatar answered Sep 23 '22 17:09

doublehelix