Nullable Types as out Parameter


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,
 
Ad

Advertisements

G

Guest

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
 
J

Jon Skeet [C# MVP]

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.
 
Ad

Advertisements

S

senfo

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top