views:

777

answers:

4

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?

+2  A: 

You might find this link on Argument validation using attributes and method interception useful

Joe
A: 

See also http://stackoverflow.com/questions/792531/c-how-to-implement-and-use-a-notnull-and-canbenull-attribute for more information on Code Contracts, how they can be implemented today in VS2008, and how they will be integrated into VS2010.

Robert Harvey
+1  A: 

Check the Enterprise Library's Policy Injection Application Block.

Fernando
+5  A: 

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();
Reed Copsey