Method that does conditional return of method calling it?
Posted
by Mattias Konradsson
on Stack Overflow
See other posts from Stack Overflow
or by Mattias Konradsson
Published on 2010-04-03T08:41:32Z
Indexed on
2010/04/03
8:43 UTC
Read the original article
Hit count: 340
c#
|code-contracts
Ok this might be a bit of hack but bear with me :) The background is that i'm tired of methods that that some if-statement to that messes up indention for the whole method, like:
public SomeClass DoStuff(string inputStr)
{
SomeClass result =null;
if (IsOpenFilter(inputStr))
{
....
}
return result;
}
So I was thinking , wouldn't it be neat if I could do something like this instead:
public SomeClass DoStuff(string inputStr)
{
Require(IsOpenFilter(inputStr),null);
....
return result;
}
The idea is that if the statement does not evaluates to true it would return null. If there wasn't a return type for the method it would simply be: Require(IsOpenFilter(inputStr));
I realize that this is kinda overlapping with code contracts but these would be more like "conditional" or "soft" contracts evaluated at runtime rather than compile time.
So I guess there's two questions, can this be done somehow? I'm stumped on how to do a conditional return from calling a method.
The other question is, is this a good idea? It's a bit weird to monkeypatch the language like this but I'd rather like the way the code reads. I would be even cleaner if it could be put into an attribute above the method: [Require(IsOpenFilter(inputStr))]
© Stack Overflow or respective owner