tags:

views:

145

answers:

2

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)?

+6  A: 

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 */));
Michael Haren
Casting is not ideal for getting the value, it's unclear if the intention was to make a conversion or not. The GetValueOrDefault method is clearer than both the coalesce operathr and the conditional operator.
Guffa
@Guffa: highly subjective. For someone that knows the language, GetValueOrDefault is verbose and coalesce is as clear as it gets. Agree with the casting part though.
Martinho Fernandes
@Guffa: wasn't the coalesce operator introduced exactly for the use with nullable types?
dtb
+9  A: 

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
Guffa
+1--didn't know about the .Value property
Michael Haren
Thanks so much!
Teddy