Diin
Diin

Reputation: 585

Setting nullable int to zero if value is less than zero

Using c# I was wondering if there is a way to cast an int to return 0 if null or less than 0

  number = ((int?) nullableNum) ?? 0

This will return 0 if null but I want a way to return 0 if less than 0

Upvotes: 3

Views: 4974

Answers (3)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23258

You can use the following syntax for that

var number = nullableNum.HasValue && nullableNum.Value > 0 ? nullableNum.Value : 0;

You check that nullableNum HasValue and whether it's Value greater 0 or not and return a Value. If condition is false (nullableNum is null and its value less 0), simply return 0

Another and more simple option is to use GetValueOrDefault method for that, it return the default value for underlying type (0 for int)

var defaultValue = nullableNum.GetValueOrDefault();
var number = defaultValue < 0 ? 0 : defaultValue;

Upvotes: 1

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26645

You can use Math.Max for that purpose, which will make the code more readable:

var number = Math.Max(0, nullableNum ?? 0)

or even better to use GetValueOrDefault instead of null-coalescing. It retrieves the value of the current Nullable<T> object, or the default value of the underlying type which is 0 for Nullable‹int›

var number = Math.Max(0, nullableNum.GetValueOrDefault());

Upvotes: 8

Aurel Savoiu
Aurel Savoiu

Reputation: 11

If you want an one-liner you could do (where nullable is your value or null):

int? nullable = null;
int zero = (nullable < 0 ? 0 : nullable) ?? 0;

Upvotes: 0

Related Questions