Click here to Skip to main content
16,004,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a variable which is in data type LONG. Is there any possibility the value being passed will turn in null value such as ""?

Below are my codes,

C#
private long UnitHeaderId;

if(UnitHeaderId != 0)
{
   //do something here
}
else
{
   //do something here
}


If the UnitHeaderId is null or empty(although with very low possibility that it would happen), will the IF statement still get executed or would it straight execute the ELSE statement? Thank you.
Posted
Comments
Tomas Takac 17-Mar-15 6:11am    
Long value cannot be null or empty. Are you parsing the number from a string?

The variable "UnitHeaderId" you declared can never be null.
It's default value is 0.

If you want to have a nullable variable you must declare it like this:
C#
long? UnitHeaderId;

The question mark indicates that the variable is nullable.
More information about nullable types can be found here:
https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx[^]
 
Share this answer
 
Primitives types (like long, int, short, and their unsigned counterparts ulong, int, ushort, etc.) cannot be null, by design.

So, in your code, the only way for the else part to be reached would be when UnitHeaderId equals zero. UnitHeaderId will never be null. The only way to handle null values for primitive types is to use them with Nullable<T> type. This way:
C#
Nullable<long> nullableUnitHeaderId;
// OR
long? nullableUnitHeaderId;
</long>
 
Share this answer
 
v2
This is something you can quite easily find out for yourself...

Try the code as it stands ... it won't compile -
Quote:
Use of unassigned local variable 'UnitHeaderId'
So try changing it to
long UnitHeaderId = null;
It still won't compile
Quote:
Cannot convert null to 'long' because it is a non-nullable value type
Now try faking a means of getting null into the variable at run-time... this will compile
C#
long UnitHeaderId;
long? x = null;
UnitHeaderId = (long)x;

if(UnitHeaderId != 0)
but as soon as you run it you get the runtime exception
Quote:
Nullable object must have a value.

So to answer your question, neither the IF nor the OR clause will be executed - if you somehow manage to get a null into UnitHeaderId you will get an exception thrown
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900