Automatically generate precondition guards in a method body from a set of custom attributes declared on a method's signature (implemented using the Roslyn API)
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

What are AutoGuards

AutoGuards is a experimental library built on top of the C# compiler-as-a-service (Roslyn). It allows a method's parameters to be marked up with custom attributes which will automatically emit guard clauses at compile time.


Instead of having to manually write guard clauses like this

public void PerformSomeCalculation(SomeObject1 obj1, SomeObject2 obj2)
	if(obj1 == null)
		throw new ArgumentNullException("obj1");
	if(obj2 == null)
		throw new ArgumentNullException("obj2");


You can instead write the method like this

public void PerformSomeCalculation(
	[NotNull] SomeObject1 obj1, 
	[NotNull] SomeObject2 obj2)

The guard clauses are automatically emitted at compile time.


The idea for this library came after thinking about the relation between interfaces and contracts.An interface definition seems a little one-sided in that it only documents the obligations of theimplementor. It says nothing about the obligations of the consumer. For example, an interface may define a contract that says that implementors must provide an implementation for aparticular method with three arguments. The interface doesn't document that the contract will only be fullfilled if the consumer promises to call that method with non-null arguments. Once an interface method definitions had been annotated with the custom attributes then any implementors would get the guard clauses inserted into their implementations for free at compile time.