int value=0; if (value == 0) { value = null; }
How can I set value
to null
above?
Any help will be appreciated.
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.
Integer int = null; int is a reserved keyword; this isn't valid Java syntax. Besides, the OP isn't referring to primitives.
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.
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.
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
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;
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.
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