0

I am very new in C# (I came from Java) and I have the following question.

In an application, on which I am working, I found something like it in the code:

if (!String.IsNullOrEmpty(u.nome))

This code simply check if the nome field of the u object is not an empty\null string.

OK, this is very clear for me, but what can I do to check it if a field is not a string, but is a normal int?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • It is just like in Java. if(yourObject != null) – Heslacher Feb 20 '14 at 09:54
  • What Heslacher said, except that `int` can't be null, as simple as that :) In any case, `string.IsNullOrEmpty` is a shortcut, and an intent-showing way of checking for "emptyness" of a string. It's effectively equivalent to writing `u.nome == null || u.nome == string.Empty`. – Luaan Feb 20 '14 at 09:55
  • @Luaan, that`s why i have written yourObject ;-) – Heslacher Feb 20 '14 at 09:56

5 Answers5

7

int? is a nullable integer. Just compare it with null

if (u.NullableInt != null)

or use Nullable<T>.HasValue property (it's matter of taste, but I found this option more readable)

if (u.NullableInt.HasValue)

NOTE: If you are asking about int then its a value type and it cannot have null value. Default value for integer is 0 (but you cannot say if it was assigned to variable or not, thats why nullable type was introduced).

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • You could also use **not null** [instead of](https://stackoverflow.com/questions/70011022/is-there-a-difference-between-and-is-not-in-c) **!=**. – Flimtix Feb 24 '22 at 07:27
1

You can use a few different types, but the most common are:

if(someVar != null) 

And if you're coming from a DB, this is particularly helpful

if(someVar != DBNull.Value)
laminatefish
  • 5,197
  • 5
  • 38
  • 70
0

int is a non-nullable value type, so it can't be null anyway. But for nullable value types (e.g., int?, bool?) and reference types (any class), you can simply compare with null

if(myObj != null) {....}
dcastro
  • 66,540
  • 21
  • 145
  • 155
0

If it is a value type like int, it will have an init value even you don't init it. For int, it's 0.

For a reference type, I think you can check like:

if(someVar != null)

You can see Value and Reference Types.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
clijiac
  • 117
  • 3
0

You can check using this mechanism:

static bool CheckIfNullOrDefault<T>(T value)
{
    return object.Equals(value, default(T));
}

double d = 0;
CheckIfNullOrDefault(d); // true
MyClass c = null;
CheckIfNullOrDefault(c); // true

Here in the above code, you find T is a reference type. Here it is compared with null. If it has some value, say Boolean, it is false. For double Default(T) is 0d, and it gets validated.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shiva Saurabh
  • 1,281
  • 2
  • 25
  • 47