I have an abstract dataprovider, with lots of methods.
In the implementation, every method needs to do some check, before continuing with the rest of the method. This check is always the same.
So now in every method, I do this:
public override string Method1 {
if(myCheck()) throw new Exception(...);
...Rest of my method1...
}
public override string Method2 {
if(myCheck()) throw new Exception(...);
...Rest of my method2...
}
public override string Method3 {
if(myCheck()) throw new Exception(...);
...Rest of my method3...
}
you get the point..
Is there an easier / better / shorter way to do this?
There is no built in feature for this in C#. You can do it in PostSharp though.
public sealed class RequiresCheckAttribute : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs e)
{
// Do check here.
}
}
If you want to do this in plain C#, a minor improvement that can make your life easier is refactoring the code into a separate method:
public void throwIfCheckFails() {
if(myCheck()) throw new Exception(...);
}
public override string Method1 {
throwIfCheckFails();
// ...Rest of my method1...
}
This doesn't force every method to perform the check - it just makes it easier.