Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Argument validation: null/empty strings

I don't know how many countless times I've had to write code to validate string arguments:

public RoomName(string name)
{
    if (string.IsNullOrEmpty(name))
    {
        throw new ArgumentException("Cannot be empty", "name");
    }
}

Is there anyway to avoid this? Is there some attribute or design-by-contract mechanism to avoid this? Is there no way to say:

public RoomName(NotNullOrEmptyString name)
{

without having to actually create that type?

like image 606
core Avatar asked Jul 10 '09 00:07

core


1 Answers

You can do that via code injection with attributes.

Another option to save some coding time, but still give you a lot of control, would be to use something like CuttingEdge.Conditions. This provides a fluent interface for argument checking, so you can write:

name.Requires().IsNotNull();
like image 68
Reed Copsey Avatar answered Oct 12 '22 23:10

Reed Copsey