Sign In Register

How can we help you today?

Start a new topic

Prevent Nulls in C# with Coalescing

Let's say you have this:

int amt = (int)virtualGood.CurrencyCosts.GetLong("gold");

If you set something up wrong, you get a null error since this is a Nullable <int?> type

Instead, use coalescing:

int amt = (int?)virtualGood.CurrencyCosts.GetLong("gold") ?? 0;

If it's null, substitute it for a 0.

Correct me if I'm wrong, but for nullable values, you can chain this as many times as you'd like. 

string a = null;

string b = null;

string c = "notNull";

string test = a ?? b ?? c;

1 Comment

You can use GetValueOrDefault() instead.

int amt = virtualGood.CurrencyCosts.GetLong("gold").GetValueOrDefault();

1 person likes this
Login to post a comment