Reputation: 73
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)
?
Upvotes: 7
Views: 5618
Reputation: 700312
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
Upvotes: 19
Reputation: 108246
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 */));
Upvotes: 6