Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: passing nullable variable to method that only accepts nonnull vars

Tags:

c#

nullable

I have code that is similar to this:

public xyz (int? a)
{
  if (a.HasValue)
  { 
    // here DoSomething has parameters like DoSomething(int x)
    blah = DoSomething(a);

I am getting the error (cannot convert from int? to int). Is there a way I can pass the variable 'a' to my function without having to do DoSomething(int? x)?

like image 309
Teddy Avatar asked Nov 10 '09 01:11

Teddy


2 Answers

Use the Value property of the nullable variable:

public xyz (int? a) {
  if (a.HasValue) { 
    blah = DoSomething(a.Value);
    ...

The GetValueOrDefault method might also be useful in some situations:

x = a.GetValueOrDefault(42);  // returns 42 for null

or

y = a.GetValueOrDefault(); // returns 0 for null
like image 60
Guffa Avatar answered Nov 02 '22 03:11

Guffa


You can cast the int? to an int or use a.Value:

if (a.HasValue)
{ 
  blah = DoSomething((int)a);

  // or without a cast as others noted:
  blah = DoSomething(a.Value);
}

If this is followed by an else that passes in a default value, you can handle that all in one line, too:

// using coalesce
blah = DoSomething(a?? 0 /* default value */);

// or using ternary
blah = DoSomething(a.HasValue? a.Value : 0 /* default value */);

// or (thanks @Guffa)
blah = DoSomething(a.GetValueOrDefault(/* optional default val */));
like image 43
Michael Haren Avatar answered Nov 02 '22 04:11

Michael Haren