Nullable Types as out Parameter

  • Thread starter Thread starter senfo
  • Start date Start date
S

senfo

I'm trying to pass a Nullable type as a parameter to the TryParse()
method (both int and float types) and I'm not having any luck. I've
tried casting as well as passing just the T.Value property; however,
doing this generated a compiler error indicating that it's not possible
to pass a property as an out or ref parameter.

Other than using a temporary (non-nullable) variable, I haven't been
able to come up with a solution.

Example:

int? MyInt;

if (!TryParse("123", out MyInt))
[...]


Any ideas?

Thank you in advance,
 
make an overload of your TryParse Method as the following

private bool TryParse(string s, out int? param)
{
param = 1;
return true;
}

private bool TryParse(string s, out int param)
{
param = 1;
return true;
}
and then use it normally
--
Muhammad Mosa
Software Engineer & Solution Developer
MCT/MCSD.NET
MCTS: .Net 2.0 Web Applications
MCTS: .Net 2.0 Windows Applications
 
senfo said:
I'm trying to pass a Nullable type as a parameter to the TryParse()
method (both int and float types) and I'm not having any luck. I've
tried casting as well as passing just the T.Value property; however,
doing this generated a compiler error indicating that it's not possible
to pass a property as an out or ref parameter.

Other than using a temporary (non-nullable) variable, I haven't been
able to come up with a solution.

Well, you could write your own utility method which used the temporary
variable approach if you need to do this a lot, but no, you can't do it
directly. The type of an out/ref parameter must be *exactly* the same
type as the one in the declaration.
 
Jon said:
Well, you could write your own utility method which used the temporary
variable approach if you need to do this a lot, but no, you can't do it
directly. The type of an out/ref parameter must be *exactly* the same
type as the one in the declaration.

Interesting. And here I thought I was loosing my mind for not being
able to find a more direct approach.

Thank you very much for your help,
 
Back
Top