If I have a void method I can do something like this to break out of it early
public void CheckIntNotLessThanZero(int value)
{
if (int < 0)
{
return;
}
Console.WriteLine("Not less than zero!")
}
However I run that exact same check several times and so I want to put it into its own method so I don't repeat code:
public void CheckIntNotLessThanZero(int value)
{
return CheckIntValue(value);
Console.WriteLine("Not less than zero!")
}
public void CheckIntValue(int value)
{
if (value < 0)
{
return;
}
}
That's a basic example but is there a way to do this?
Turn your Check...
methods to return bool
value, and check it after every call:
public bool CheckIntValue(int value)
{
return value < 0;
}
public void CheckIntNotLessThanZero(int value)
{
if (CheckIntValue(value))
return;
Console.WriteLine("Not less than zero!")
}
Note, that you could throw exceptions in Check...
methods, but you must not . To manage execution flow using exceptions is a bad practice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.