user72603
user72603

Reputation: 1007

Integer validation

stupid question but this statement is worthless

int a;

if (a != null)

since an integer var is automatically set to null by the compiler when defined

to check integers always check if a >= 0 correct?

Upvotes: 0

Views: 1068

Answers (5)

Jim H.
Jim H.

Reputation: 5579

An int is a value type and will never be null, unless you declare it as a nullable integer:

int? i = null;
if (i == null)
    Console.WriteLine("it's null");

Upvotes: 0

user1921
user1921

Reputation:

Assuming by your tag & syntax this is C#, have you tried int.TryParse(...) in your particular scenario? Not really sure what you're trying to do from the code provided - as Andy mentioned if your int is nullable the null check might be useful.

Upvotes: 0

sipsorcery
sipsorcery

Reputation: 30734

Yes unless the integer happens to be a nullable type.

int? myInt = null;

if(myInt == null)
{
    Console.WriteLine("myInt was null.");
}

Upvotes: 0

Andy White
Andy White

Reputation: 88475

The compiler sets the value of a primitive variable to its "default" value if you don't assign it. The default value of int is 0. So yeah, the comparison you mention doesn't really do anything.

If you need a nullable int in your code you should use the "nullable" type "int?".

If your int is nullable, then the comparison you mention might be useful.

Upvotes: 2

Reputation:

int is a class, not equal to null

Upvotes: 0

Related Questions