Reuse the Same Variable For Multiple TryParse() Calls
-
12-06-2021 - |
Вопрос
I did some reading on this, and from questions similar to mine, it looks like what I am about to ask might not be (easily) possible... But I wanted to verify anyway. Maybe all those questions were from an older version of C#/.NET, and the thing has been implemented recently.
Anyway. I have a switch-case statement in one of my classes, whose purpose is essentially to take an int (typeID
) and string (value
) and check whether the value
can be parsed as the data type indicated by typeID
. For example, here is part of what I have now:
case 1:
char charret;
return char.TryParse(value, out charret);
case 2:
Regex re = new Regex(Constants.REGEX_ALPHANUMERIC);
return re.IsMatch(value);
case 3:
bool boolret;
return bool.TryParse(value, out boolret);
//And so on...
What I would like to do is to be able to avoid the char
/bool
instantiation you see in cases 1 & 3. Ideally, I would like to just have the return statement. It's not a big deal (obviously), but it would be nice if I could make this more (even more) compact.
Решение
That's inherently impossible.
Variables passed as out
parameters must exactly match the parameter type.
Другие советы
There's no way to avoid declaring a variable when you are calling a function with an out parameter.
This post might be helpful as it does a generic TryParse (if it is available):
http://toadcode.blogspot.com/2010/10/generic-object-tryparse.html