I'm trying to implement a "return if"/"return value if" without an else case, since I only want to return or return a value if a condition is valid.
I know, there is the if (condition) return;
or if (condition) return value;
but I want to have the code a bit cleaner AND it would be nice to have that syntax since it is more readable.
I heard with roslyn this is possible and read the question with its answeres here: Is there a way to implement custom language features in C#? but I have no clue how to implement it.
So the code would be something like this:
public class Testclass
{
public static void Main(String[] args)
{
Testclass t = new Testclass();
t.TestMyClassWithVoid();
bool success = t.TestMyClassWithInt(3) == 3;
bool fail = t.TestMyClassWithInt(2) == 2;
}
public void TestMyClassWithVoid()
{
int value = GetValueFromSomeWhere();
return if value == 3;
DoSomeOtherStuffSinceValueIsNotThree();
}
public int TestMyClassWithInt(int value)
{
return value if value == 3;
DoSomeOtherStuffSinceValueIsNotThree();
return -1;
}
}
any idea how I could solve this? I started trying with the Roslyn.Compilers.CSharp
-namespace but I have no clue how to start implementing.