Home > C# > Performing several validations in C#

Performing several validations in C#

In the project I’m working on, one of the requirements about error handling was that a lot of things could be validated at the same time and it shouldn’t stop validating when some fails. As the errors are treated as exceptions and exceptions breaks the method flow, it’s obvious that we can’t make the validations left when an exception occurs.

So, I start thinking about a validation scope where there are no rules, everything is possible. But when the scope ends, all the exceptions are thrown.

public void PerformOperation(string param1, int param2)
{
     using (var validationScope = new ValidationScope())
     {
          validationScope
            .When(string.IsNullOrEmpty(param1))
            .Throw<InvalidParam1Exception>();
     
          int something = DoSomethingWith(param1);
 
          validationScope
            .When(something < 10)
            .Throw<InvalidSomethingException>();

          validationScope.Try( () => DoSomethingThatCouldFail(param1) );
     }
     //Do whatever this method should do
}

Basically, ValidationScope methods executes the delegates and conditions and stores the exceptions in a private collection. When the scope is disposed, the exceptions are thrown as one CompositeException containing each of them.

Nice, isn’t it?
You can download the complete source code from here.

Advertisements
Categories: C# Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: