Delegates To Lambdas Cheat Sheet

A cheat sheet Delegates & Lambdas in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

// DELEGATE DEFINITION
public delegate bool IsGreaterThan(int aParam, int compareTo);

// CREATION AND ASSIGNMENT

// .Net 1 version
IsGreaterThan isGreaterThanHandler = new IsGreaterThan(DelegatesToLambda.IsGreaterThanImplementation);

A cheat sheet for Ninject IOC Frmaework in C#

All source code can be found on GitHub <a href="https://github.com/lukewickstead/DOT-NET-on-Linux">here</a>.

// Method Group Conversion
IsGreaterThan isGreaterThanHandler = IsGreaterThanImplementation;

// Anonymous Function
IsGreaterThan isGreaterThanHandler = delegate(int aValue, int compareTo) { return aValue > compareTo; };

// Lambda Functions
IsGreaterThan isGreaterThanHandler = (int aValue, int compareTo) => { return aValue > compareTo; }; // Full hand
IsGreaterThan isGreaterThanHandler = (aValue, compareTo) => { return aValue > compareTo; }; // Param type inferrence
IsGreaterThan isGreaterThanHandler = (aValue, compareTo) => aValue > compareTo; // One line in method + return inferred
IsGreaterThan isGreaterThanHandler = aValue  => aValue > 1; // One param
IsGreaterThan isGreaterThanHandler = ()  => 2 > 1; // No params

// DELEGATES AND GENERICS

// Definition
public delegate string ConcatToString(T aValue, T compareTo);

// .Net 1 version
ConcatToString concatToStringHandler = new ConcatToString(DelegatesTestsWithGenerics.ConcatToStringImplementation);

// Method Group Conversion
ConcatToString concatToStringHandler = DelegatesTestsWithGenerics.ConcatToStringImplementation;

// Anonymous Function
ConcatToString concatToStringHandler = delegate(int aValue, int bValue) { return string.Format("{0}{1}", aValue, bValue); };

// Lambda Function
ConcatToString concatToStringHandle = (aValue, compareTo) => string.Format("{0}{1}", aValue, compareTo);

// FUNC<T, TResult>, ACTION PREDICATE

// Func, Action & Predicate are global delegates definitions to save creating your own.

// Func
// Func can take up to 16 parameter types and return one type

// Parameters expecting  a Func will looks something like
// Func
// Func<T, TResult>
// Func<T, T, TResult>
// Func<T, T, T, TResult>
// Func<T, T, T..... TResult>

Func<int, int, string> aHandler = delegate(int aInt, int bInt) { return string.Empty; }; // Anonymous Method
Func<int, int, string> cHandler = (anInt, anotherInt) => string.Empty; // Lambda

// Predicate can take up to 16 parameters and retun a bool
// Parameters expecting  a Predicate will looks something like
// Predicate<T, TResult>
// Predicate<T, T, TResult>
// Predicate<T, T, T, TResult>
// Predicate<T, T, T..... TResult>

Predicate aHandler = delegate(int anInt) { return anInt > 1; }; // Anonymous Method
Predicate cHandler = anInt => anInt > 1; // Lambda

// Action can take up to 16 parameters and retuns a null
// Parameters expecting  a Action will looks something like
// Predicate
// Predicate<T, T>
// Predicate<T, T, T>
// Predicate<T, T, T....., T>

Action aHandler = delegate(int x) { throw new Exception(); }; // Anonymous Method
Action bHandler = x => { throw new Exception(); };       // Lambda

// MULTICAST DELEGATES
// Multiple events can be registered and deregistered with += and -=
// All events are called one at a time.
// Last one returns the value.
IsGreaterThan isGreaterThanHandler = IsGreaterThanImplementation;
isGreaterThanHandler += IsGreaterOrEqual;
isGreaterThanHandler(1,2);
isGreaterThanHandler -= IsGreaterOrEqual;

// EVENTS
// Events are shorthand notation of grouping delegates
public delegate bool IsGreaterThan(int aParam, int compareTo);
public event IsGreaterThan IsGreaterThanEvent;
IsGreaterThanEvent += IsGreaterThanImplementation;
IsGreaterThanEvent += IsGreaterOrEqual;
IsGreaterThanEvent(1,2);
IsGreaterThanEvent -= IsGreaterOrEqual;

// CONTRAVARIANCE
Contravariance allows us to a method which has a parameter which is a child class of the defined parameter.

// COVARIANCE
Allows us to return a type which is a child class of the defined delegate return type

Advertisements

NInject Cheat Sheet

A cheat sheet for Ninject IOC Frmaework in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

You can also view my HowTos  here and here


// **** DETERMINING WHICH CONSTRUCTOR TO USE ****
// The main DI pattern is Constructor Injection
// A known constructor parameter is one which has been explicitly bound
// An unknown constructor parameter is one which has not been explicitly bound even if it has a resolvable constructor the following order defines which constructor is used
// 1. User defined costructor marked with [Inject] attribute
// 2. The constructor with the most known bound parameters.
// 3. The default parameterless constructor

// **** PROPERTY / METHOD INJECTION
// Properties and methods marked with the [Inject] property will be resolved imediatly after the selected constructor
// Properties are required to be public set and private get
// Methods should be public and return void

[Inject]
public void AMethod(IClass aClass)
{
    this.aClass = aClass;
}

[Inject]
public IClass Property { private get; set; }

// **** BIND TO ****
// Classes are automatically bound to themselves
Bind<IClass>().ToSelf( )			// Explicit self binding
Bind<IClass>().To<Class>();  			// Bind to class
Bind<IClass>().ToConstant( )			// Binding with constant (the returned class), implicitly sets scope to InSingletonScope
Bind<IClass>().ToConstructor( )			// Bind with constructor
Bind<IClass>().ToMethod( )			// Binding with method
Bind<IClass>().ToProvider( )			// Binding with provider, class with parent of Provider<T> allowing addressing of complex initiation

// **** BINDING SCOPE ****
// The lifetime of an instance can be defined via the scope of the binding
// The default scope is InTransientScope
kernel.Bind<IClassA>().To<B>(ClassA).InTransientScope()  	// Always create an instance per Get call
kernel.Bind<IClassA>().To<B>(ClassA).InSingletonScope()		// Create only one instance
kernel.Bind<IClassA>().To<B>(ClassA).InThreadScope()		// Create one instance per thread and always return this
kernel.Bind<IClassA>().To<B>(ClassA).InRequestScope()		// Create one instance per web request and return this
kernel.Bind<IClassA>().To<B>(ClassA).InScope(Func<object>)	// Returns an object associated with the lifetime. The same instances is returned for the same life time of this associated lifetime object. Once this has been garbage collected our bound object will be recreated

// **** CONDITIONAL BINDING ****
Bind<IClass>().To<Class>().Named("AName");  				// Named Binding
Bind<IClass>().To<Class>().WithConstructorArgument("Iclass", delegat/object); // Constructor Argument
Bind<IClass>().To<Class>().WithMetadata("AMetaName", false); 		// Derrived Attribute Bindings
Bind<IClass>().To<Class>().WithParameter(new ConstructorArgument/Property("IClass/PropertyName", new XYZ() ); // WithConstructorArgument is a short cut to this
Bind<IClass>().To<Class>().WithPropertyValue(ProprtyName, delegate/object); // Explicit property injection
Bind<IClass>().To<Class>().When();					// Explicit Conditional binding
Bind<IClass>().To<Class>().WhenAnyAnchestorNamed("AnyParentInAncestry"); // When any class in ancestry is named
Bind<IClass>().To<Class>().WhenClassHas<AnAttribute>();  		// Binding with attributes based helpers
Bind<IClass>().To<Class>().WhenInjectedInto(typeof(AClass)); 		// Conditional injected into AClass or any derrived classes
Bind<IClass>().To<Class>().WhenInjectedExactlyInto(typeof(AClass));	// Conditional injected into AClass and not any derrived classes
Bind<IClass>().To<Class>().WhenMemberHas<AnAttribute>();  		// Binding with attributes based helpers
Bind<IClass>().To<Class>().WhenParentNamed("ParentName");		// Bind when the direct parent is named
Bind<IClass>().To<Class>().WhenTargerHas<AnAttribute>(); 		// Binding with attributes based helpers

// **** MULTIPLE BINDING WITH BindingConfiguration ****
// Default bind up to 4 however more can be found via caching and provinding the bind config.
var bindingConfiguration =
    Bind<IInterface1, IInterface2, IInterface3, IInterface4>()
        .To<Implementation>()
        .BindingConfiguration;
kernel.AddBinding(new Binding(typeof(IInterface5), bindingConfiguration));
kernel.AddBinding(new Binding(typeof(IInterface6), bindingConfiguration));

// **** OnActivation AND OnDeactivation EVENTS
// Trigger evets on the activation and deactivation
Bind<IClass>().To<Class( ).OnActivation( x => x.ActivationMethod())		// Called when an object is activate (instantiated)
Bind<IClass>().To<Class( ).OnDeactivation(x => x.DeactivationMethod())		// Called when an object is deactivate (disposed?)

// **** KERNEL CREATION ****
IKernel kernel = new StandardKernel();

// *** KERNEL MODULES ***
// Provide a grouping of registring bindings
public class WarriorModule : NinjectModule
{
    public override void Load() { } 	// Binding code goes in here
    public override void OnLoad() { } 	// OnLoad event
    public override void OnUnLoad() { } // OnUnload event
}

IKernel kernel = new StandardKernel(new AKernelModule());
IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);
kernel.Load/UnLoad("*.dll"); // Load / Unload all Kernel Modules within dll
kernel.Load.UnLoad(AppDomain.CurrentDomain.GetAssemblies()); // // Load / Unload all Kernel Modules within the current domains dll's

// **** GET / RESOLVE / INJECT ****
// During execution of code request instance of injected class via the kerel
// Any classes passed in as parameters to the constructor or INJECT marked methods/properties will be automatically resolved.
var aClass = kernel.Get<IClass>();
var classes = kernel.Get<IWarrior>( new ConstructorArgument( "IClass", new AClass() ) );
var classes = kernel.GetAll<IClass>();

// **** MULTIPLE BINDINGS
public ClassName( IEnumerable<IClass> classes) // An instance off all classes implementing the interface will be injected in

// **** NAMED BINDING ****
Bind<IClass>().To<ClassA>().Named("First"); 	// Name the binding during binding
Bind<IClass>().To<ClassB>().Named("Second");
kernel.Get<IClass>("First"); 			// Resolve the bind by providing the name
public ClassC ( [Named("First") IClass aClass]  // Consuctors, Methods and Properties can have named parameters to resolve their injection

// **** DERRIVED ATTRIBUTE BINDINGS ****
// Define an attribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class IsSomething : ConstraintAttribute {
    public bool Matches(IBindingMetadata metadata) {
        return metadata.Has("IsSomething") && metadata.Get<bool>("IsSomething");
    }
}

Bind<IClass>().To<AClass>().WithMetadata("IsSomething", false);
Bind<IClass>().To<BClass>().WithMetadata("IsSomething", true);

public AnotherClass([IsSomething] IClass aClass) {} // face resolves to BClass

// TODO: try this bit
kernel.Get<IClass>(metadata => metadata.Has("IsSomething") && metadata.Get<bool>("IsSomething") == false ) // resolves to AClass

// **** BINDING WITH ATTRIBUTE BASED HELPERS ****
// The Target: the parameter being injected into
// The Member: the property, method or constructor itself
// The Class: the class Type within which the Member or Target is defined within

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class WhenClassHas : Attribute{ }

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class WhenMemberHas : Attribute{}

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class WhenTargetHas : Attribute{}

public class InjectWhenMemberAndTargetHas
{
	[Inject, WhenMemberHas]
	public IClass WhenMemberHas { get; set; } // Member has an attribute
	public IClass WhenTargetHas { get; set; }
	public InjectWhenMemberAndTargetHas([WhenTargetHas] IClass aClass){WhenTargetHas = aClass;} // target has an attribute
}

[WhenClassHas]
public class InjectWhenClassHas
{
	[Inject] // Class is marked with attriibute. binding is done by class
	public IClass WhenClassHas { get; set; }
}

Bind<IClass>().To<KnownC>().WhenClassHas<WhenClassHas>();
Bind<IClass>().To<KnownD>().WhenTargetHas<WhenTargetHas>();
Bind<IClass>().To<KnownE>().WhenMemberHas<WhenMemberHas>();

// **** BIND WITH METHOD ****
// Used to bind to factory methods.
// Here we are passing in the reques5 context tyoe
Bind<IClass>().ToMethod( context => AFactory.Create( context.Request.Target.Type ) )
Bind<IClass>().ToMethod( x => new ClassC(x.Kernel.Get<IClassA>(), x.Kernel.Get<IClassB>()));

// **** BIND TO PROVIDER ****
// Binding with provider, class with parent of Provider<T> allowing addressing of complex initiation
Bind<IClass>().ToProvider(new AProvider())

public class AProvider : Provider<AClass>
{
    protected override AClass CreateInstance(IContext context)
    {
        return new AClass(); // Do some complex initialization here.
    }
}

// **** BIND TO CONSTRUCTOR ****
Bind<IMyService>().ToConstructor( ctorArg => new ClassC(ctorArg.Inject<IClassA>(), ctorArg.Inject<IClassB>())); // TODO what is the difference between constructor and method binding

// **** BIND WITH CONSTRUCTOR ARGUMENT ****
Bind<IClass>().To<Class>().WithConstructorArgument("ParameterName", x =>x.Kernel.Get<IClass>()); //

// **** BIND WITH EXPLICIT CONDITIONAL BINDING ****
Bind<IClass>().To<ClassA>().When(request => request.Target.Member.Name.StartsWith("ClassName"));
Bind<IClass>().To<ClassB>().When(request => request.Target.Type.Namespace.StartsWith("NameSpace.ClassName"));

Generics Cheat Sheet

A cheat sheet for Generics in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

My How To in Generics can be found here while some code examples can be found in my post here.


// **** WHY GENERICS ****
// Type Safe: Prevent having to cast between obect and a type when retrieving data from objects such as classes

// Faster: Value types which are placed into classes which are designed to be used on multiple types. No need to box/unbox value types.
// Allocating an object on the heap from the stack and vice versa is slow

// **** WHEN SHOULD I USE GENERICS ****
// When you have multiple method overloads which have the same functionality for multiple types

// *** WHEN SHOULD I NOT USE GENERICS ****
// If you find yourself restrcting access to an Interface or a base class then you should ask yourself if generics is really required here

// **** CONSTRAINTS ****
// Constrains provide a way to limit which types can be used
// In most cases no constraintss should be used
where T: struct 	// Value Type; System.ValeValue is found as an ancestor
where T: class 		// Reference type; System.ValeValue is not found as an ancestor (any class, interface, delegate or array type)
where T: new() 		// Provides a parameterless constructor.
where T:  	// Has an ancestory
where T:  	// Implements an interface
where T: U 		// One provided type is an ancestor of another.

// Examples
class Test<T, U> where U : struct where T : Base, new() {}
class List{ void Add<span style="text-decoration: underline;">(List<span style="text-decoration: underline;"> items) where U : T {}
class SampleClass<T, U, V> where T : V {}
void SomeFunction(T aValue) where T : V {}

// **** EQUALITY  ****
// Can not use != & == operators as we can not gurantee that concrete type will implement these
// Can compare to null though for value types will always return false.

// **** DEFAULT VALUE ****
return default(T); // returns the default value of the type; 0 for int etc.

// **** CASTING ****
// Can cast to and from System.Object and explcitly convert to any interfaces.
// Implicit cast can be to object or to constraint-specified types only.
// Implicit casting is type safe as incompatibility is discovered at compile-time.
// Explicit cast can be to interface only

// Consider
class MyClass where T : BaseClass, ISomeInterface {}

//Implicit
ISomeInterface obj1 = t;
BaseClass      obj2 = t;
object         obj3 = t;

// Explicit
ISomeInterface obj1 = (ISomeInterface)t;	//Compiles
SomeClass      obj2 = (SomeClass)t;     	//Does not compile

// Explcity achieved via temp object; is dangerous. better to use is or as operator
object temp = t;
MyOtherClass obj = (MyOtherClass)temp;

// Can Cast
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
if(t is int)
if(t is LinkedList<int,string>)

// AS Cast; like a cast but returns null on failure
t as IDisposable
expression is type ? (type)expression : (type)null // equivalent to as
using(t as IDisposable)

// **** ATTRIBUTES ****
// These can not be used however you can check owning functions
myobj.GetType().IsSerializable

// **** TYPE ANALYSYS ****

// TypeCode Enum
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
TypeCode.Boolean;
TypeCode.Decimal;

// IsType
typeof(int).IsPrimitive
typeof(int).IsDecimal
typeof(int).IsArray
typeof(int).IsInterface

// Nullable Types
Nullable
t?

// **** CONVERTING BETWEEN TYPES ****
// Parse & Try Parse
Integer.Parse
Integer.TryParse( "1", out aValue)

// Change Type: Returns an object of the specified type and whose value is equivalent to the specified object.
int i = (int)Convert.ChangeType(-2.345, typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("12/12/98", typeof(DateTime));

// TypeDescriptor Converter
public static T GetTfromString(string mystring)
{
   var foo = TypeDescriptor.GetConverter(typeof(T));
   return (T)(foo.ConvertFromInvariantString(mystring));
}

Linq Cheat Sheet

A cheat sheet for Linq in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 

// **** AGGREGATE ****

// Aggregate Linq Ext methods can be applied to natural Linq
.Count()
.Min()
.Max()
.Average()
.Sum()

// Aggregate
var count = (from p in people
 		select p).Count ();

// Conditional Aggregate
var count = (from p in people
             where p.Gender == Gender.Male
             select p).Count ();

// Nested Aggregate
var samplePeople = from p in people
		   select new { Name= p.Name,
				ChildrenCount =
				  (from c in p.Children
				   where c.Gender == Gender.Female
				   select c).Count () };

// Grouped Aggregate
var children = from p in people
	group p by p.Gender into peopleGenders
		let minKids = peopleGenders.Min( x => x.Children.Count())
	select new { Gender = peopleGenders.Key, Value = peopleGenders.Count() };

// Let satement
var children = from p in people
	let x = peopleGenders.Count( x => x.Children.Count())
	select x

// **** CONVERSIONS ****
// All conversions functions should be done with Linq ext methods ToArray(), ToList(), ToDictionary(), OfType(), Cast(); see Linq Ext cheet sheet here.

// **** ELEMENT ****
// All element functions should be done with Linq ext methods First(), FirstOrDefault(), Last(), LastOrDefault(), ElementAt(); see Linq Ext cheet sheet here.

// **** FILTER ****
// Where filter
var count = (from p in people
             where p.Age < 30
             select p).Count ();

// Drilled where filter
var count = (from p in people
             where p.Children.Count () > 0
             select p).Count ();

// **** GENERATION ****
// All generation functions should be done with Linq ext methods Enumerable.Range() and Enumerable.Repeat(); see Linq Ext cheet sheet here

// **** GROUPING ****
// Group by gender and count...
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.Count()};

// Split into groups of gender by grouping on Name
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.OrderBy( x => x.Name)};

// **** ORDERING ****
// Order ASC
var orderdPeople = from p in people
	orderby p.Name
	select new { p.Name, p.Age, p.Children, p.Gender };

// Order DES
var orderdPeople = from p in people
	orderby p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

// Order by multiple fields
var orderdPeople = from p in people
	orderby p.Age, p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

// Reverses the order
var orderdPeople = (from p in people
	orderby p.Name
    select new { p.Name, p.Age, p.Gender, p.Children }).Reverse ();

// **** PARTITIONING ****
// All partitioning functions should be done with Linq ext methods Take(), Skip(), TakeWhile() SkipWhile(); see Linq Ext cheet sheet here

// **** PROJECTION ****
// Select column
var allFemaleNames = from p in people
           			where p.Gender == Gender.Female
           			orderby p.Name descending
					select p.Name;
// Select columns into anonymous type
var parentsNameAndAge = from p in people
	where p.Gender == Gender.Female
	select new { Name =  p.Name, Age = p.Age };

// Select element
var boysWithFemaleParents = from parent in people
	where parent.Gender == Gender.Female
	from children in parent.Children
	where children.Gender == Gender.Male All
	select children;

// **** QUANTIFIERS ****
// Any() and All() functions can be applied here

// Any exists
var isAnyPeople = (from p in people
                   where p.Gender == Gender.Unknown
                   select p).Any ();

// Any exists in group
var isAnyPeople = from p in people
    			  where p.Children.Any (child => child.Gender == Gender.Unknown)
				  group p by p.Gender into genders
                  select new { Gender = genders.Key, People = genders};

// **** SETS ****
// Most set functions should be done with Linq ext methods Take(), Skip(), TakeWhile() SkipWhile(); see Linq Ext cheet sheet here
// inner join between person and gender description
var foo = from aPerson in people
	join aDes in genderDescriptions on aPerson.Gender equals aDes.Gender
select new { Name = aPerson.Name, Gender = aPerson.Gender, Desc = aDes.Descripion};

Linq Extension Methods Cheat Sheet

A cheat sheet for Linq Extension Methods in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


// **** AGGREGATE ****
data.Count() 						// The count of items
data.Cout(x => x.Condition == true)			// Count items which pass criteria
data.Sum (x => x.Value); 				// Sum of all items
data.Min(x => a.Value);					// Min value
data.Max(x => a.Value);					// Max value
data.Average(x => a.Value);				// Average
data.Select(x => new { A = x.Name, B = x.Min(x.Value))	// Nested Aggregate
data.GroupBy( x => x.Type)
	.Select( y =>
	new { Key = y.Key,
	      Average = y.Average ( z => z.Value ) } ); // Grouped Aggregate

// **** CONVERSIONS ****
data.ToArray();						// Convert to Array
data.ToList();						// Convert to List
data.ToDictionary( x=> x.Name ); 			// Convert to Dictionary keyed on Name
data.OfType<decimal> ().ToList ()			// Filters out all elements not of provided type
data.Cast<decimal> ().ToList ()				// Cast can only cast to Implemented Interfaces and classes within the hierachy
data.ConvertAll<double> (x => Convert.ToDouble (x));	// Convert all items with provided conversion method

// **** ELEMENT ****
data.First()						// Returns the first element
data.First( x=> x.Type == Types.A )			// Returns the first element passing the condition
data.FirstOrDefault( )					// Returns the first element or default*
data.FirstOrDefault( x => x.Type == Types.B )		// Returns the first element passing the condition or default*
data.Last()						// Returns the last element
data.Last( x=> x.Type == Types.A )			// Returns the last element passing the condition
data.LastOrDefault( )					// Returns the last element or default*
data.LastOrDefault( x => x.Type == Types.B )		// Returns the last element passing the condition or default*
data.ElementAt(0)					// Returns the element at position 0
*default						// Default is defined as default(typeOf(T)) or new Constructor() without any constructor parameters

// **** FILTERS ****
data.Where(x => x.Type == Types.A)			// Returns all elements passing the condition
data.Where(( x, index) => index <= 4 && x.Type == Types.A) // The elements index can be passed into the delegate

// **** GENERATION ****
Enumerable.Range(1, 10);				// Creates collection of 10 items between 1 and 10
Enumerable.Repeat(1, 10);				// Creates a collection of 10 1s.

// **** GROUPING ****
// Grouping is not like SQL where columns have to be aggregates or wihtin the group list; you group the elements into a list for each group

data.GroupBy (x => x.Type)
    .Select (grp => new { Key = grp.Key, Value = grp.Count ()}); // Group with count of data

data.GroupBy (x => x.Type)
    .Select (grp => new { Key = grp.Key,  Value = grp.OrderBy (x => x.Name)}); // Create a collection of elements ordered by name for each group of Type

// **** ORDERING ****
data.OrderBy (x => x.Name);					// Order by Name ASC
data.OrderBy (x => x.Name).ThenBy (x => x.Age);			// Order by Name ASC the Age ASC
data.OrderBy (x => x.Name).ThenByDescending (x => x.Age);	// Order by Name ASC then Age DESC
data.OrderByDescending (x => x.Name);				// Order by Name DESC
data.OrderBy (x => x.Name, 					// Order by Name ASC Case insensative
	StringComparer.CurrentCultureIgnoreCase);
data.OrderBy (x => x.Name).Reverse ();				// Reverse elements

// **** PARTITIONING ****
data.Take (3);							// Take 3 items
data.Skip (3);							// Skip 3 items
data.TakeWhile (x=>x.Type ==Types.A);				// Take all the items while the condition is met
data.SkipWhile (x=>x.Type ==Types.A);				// Skip all the items while the condition is met

// **** PROJECTION ****
data.Select (x => x.Name);					// Select collection of a column
data.Select (x => new { Name = x.Name, Age = x.Age });		// Select a collection of columns through an anonymus type
data.SelectMany (x => x.Children)				// SelectMany flattens collections into one collection

// **** QUANTIFIERS ****
data.Any (x => x.Type == Types.TypeA);				// Returns True/False if any element meets the condition
data.All (x => x.Type == Types.TypeA);				// Returns True/False if all the elements meet the condition

// **** SET ****
data.Distinct ();						// Returns a collection of distinct elements
data.Intersect(dataTwo);					// Returns the union / intersection of data; elements in both collections
data.Except(dataTwo);						// Returns elements in data which are not in dataTwo
data.Concat(dataTwo);						// Concatonates both collections; appends dataTwo to data
data.SequenceEqual(dataTwo));					// Returns True if data has the same data and sequence of dataTwo
data.Join(dataTwo, 						// Joins the data together like SQL join
    x => x.Type,						// Join field on data
    y => y.Type, 						// Join field on dataTwo
    ( d1, d2 ) => new { Name = d1.Name, Type = d1.Type, Desc = d2.Descripion} ); // Selection criteria

data.Distinct (new AComparer ()).				// Distinct with providing an equality provider
public class AComparer : IEqualityComparer<A>
{
    public bool Equals (A x, A y) { return a == a;}
    public int GetHashCode (A obj) { return obj.GetHashCode(); }
}

XUnit Cheat Sheet

A cheat sheet for the XUnit test framework

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
namespace GenericsExamples.Tests
{
    public class AccountTests : IDisposable,                             // Allows Test TearDown via Dispose()
                                IUseFixture<AccountTests.TestSetUpClass> // Allows Test Set Up via injected class
    {

        public AccountTests()
        {
            // TestFixture Setup code here
            Console.WriteLine("AccountTests Constructor");
        }

        public void SetFixture(TestSetUpClass setupClass)
        {
            // Can inject a class to provide any set up here.
            setupClass.AnyFunction();
        }
        /// <summary>
        /// The very simply example.
        /// </summary>
        [Fact]
        public void SimpleExample()
        {
            Console.WriteLine("AccountTests.TestOne()");
            Assert.True(true);
        }

        /// <summary>
        /// InLineData allows multiple traversals of the same test with different parameters
        /// </summary>
        /// <param name="number"></param>
        /// <param name="expectedResult"></param>
        [Theory,
        InlineData(1, true),
        InlineData(2, true),
        InlineData(3, false)]
        public void InlineDataExample(int number, bool expectedResult)
        {
            Console.WriteLine("AccountTests.DemoSimpleTestWithInLineData(int {0}, bool {1})", number, expectedResult);
            Assert.Equal(number < 3, expectedResult);
        }

        /// <summary>
        /// Properties returning IEnumerable can be used instead of InLineData.
        /// </summary>
        public static IEnumerable<object[]> SamplePropertyDataProperty
        {
            get
            {
                yield return new object[] { 1, true };
                yield return new object[] { 2, true };
                yield return new object[] { 3, false };
            }
        }

        /// <summary>
        /// PropertyData allow multiple calls of a test function with parameters defined in a property usign yield
        /// </summary>
        /// <param name="number">Test data</param>
        /// <param name="expectedResult">Expected Result</param>
        [Theory]
        [PropertyData("SamplePropertyDataProperty")]
        public void PropertyDataExample(int number, bool expectedResult)
        {
            Console.WriteLine("AccountTests.PropertyDataExample(int {0}, bool {1})", number, expectedResult);
            Assert.Equal(number < 3, expectedResult);
        }

        /// <summary>
        /// A run throw of the most common Assertions
        /// </summary>
        [Fact]
        public void AsertionExamples()
        {
            Console.WriteLine("AccountTests.AsertionExamples()");

            Assert.Contains("n", "FNZ", StringComparison.CurrentCultureIgnoreCase);
            Assert.Contains("a", new List<String> { "A", "B" }, StringComparer.CurrentCultureIgnoreCase);

            Assert.DoesNotContain("n", "FNZ", StringComparison.CurrentCulture);
            Assert.DoesNotContain("a", new List<String> { "A", "B" }, StringComparer.CurrentCulture);

            Assert.Empty(new List<String>());
            Assert.NotEmpty(new List<String> { "A", "B" });

            Assert.Equal(1, 1);
            Assert.Equal(1.13, 1.12, 1); // Precsions Num DP
            Assert.Equal(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCultureIgnoreCase);
            Assert.Equal(GetFoo(1, "A Name"), GetFoo(1, "a name"), new FooComparer());

            Assert.NotEqual(1, 2);
            Assert.NotEqual(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCulture);

            Assert.False(false);
            Assert.NotNull(false);
            Assert.Null(null);
            Assert.True(true);

            Assert.InRange(1, 0, 10);
            Assert.NotInRange(-1, 0, 10);

            Assert.IsType(Type.GetType("System.Int32"), 1);
            Assert.IsNotType(Type.GetType("System.Double"), 1);

            var foo = new object();
            var moo = new object();

            Assert.Same(foo, foo);
            Assert.NotSame(foo, moo);

            Assert.Throws<Exception>(() => { throw new Exception(); });
            Assert.True(true);
        }

        private static Foo GetFoo(int id, string name)
        {
            return new Foo { ID = id, Name = name };
        }

        public void Dispose()
        {
            // TestFixture Teardown attributes
            Console.WriteLine("AccountTests.Dispose()");
        }

        # region Internal Classes
        public class Foo
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }

        public class FooComparer : IEqualityComparer<Foo>
        {
            public bool Equals(Foo x, Foo y)
            {
                return x.ID == y.ID && x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase);
            }

            public int GetHashCode(Foo obj)
            {
                return obj.ID.GetHashCode();
            }
        }

        public class TestSetUpClass
        {
            public void AnyFunction()
            {
                Console.WriteLine("TestSetUpClass.AnyFunction()");
            }
        }
        #endregion
    }
}

NUnit Cheat Sheet

A cheat sheet for the NUnit test framework

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 

using System;
using System.Reflection;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;

namespace NUnitCheatSheet
{
	/// <summary>
	/// TestFixtureSetUp: Provides a config class for setting up and tearing down the test fixture.
	/// Provides the config for all TestFixture classes witin the same namespace.
	/// </summary>
	[SetUpFixture]
  	public class TestFixtureSetUp
  	{
		/// <summary>
		/// SetUp; run once before all tests in a test fixture.
		/// Run once for each TestFixture in the same namespace.
		/// </summary>
	    [SetUp]
		public void RunBeforeAnyTests()
		{
		  // Set up code here.
		}
		/// <summary>
		/// TearDown; run once after all tests in a test fixture.
		/// Run once for each TestFixture in the same namespace.
		/// </summary>
	    [TearDown]
		public void RunAfterAnyTests()
		{
		  // Clear up code here.
		}
  	}

	/// <summary>
	/// Factory class for providing test data for tests with the TestCaseSource attribue.
	/// </summary>
	public class TestCaseDataFactory
	{
		/// <summary>
		/// TestCaseSource tests can consume IEnumerable properties which return TestCaseData
		/// </summary>
	  	public static IEnumerable TestCasesDataForTestCaseSourceTest
		{
		    get
		    {
		      yield return new TestCaseData( 1, "1" ).Returns( 2 ); // Defines the test data and the expected return
		      yield return new TestCaseData( 2, "2" ).Returns( 4 );
		      yield return new TestCaseData( 0, "a" )
						.Throws(typeof(ArgumentException)); // Defines the test data and the expected throw exception
		    }
		}
	}

	/// <summary>
	/// TestFixture defines a class of tests
	/// </summary>
	[TestFixture(), Category("MyTests"), Description("NUnut Cheat Sheet!")]
	public class Test
	{
		/// <summary>
		/// TestCaseSource attributes can use static properties to return an array of test data
		/// </summary>
		public static object[] CaseSourceTestData =
		{
		    new object[] { 1, 1.1m, "2.1" },
			new object[] { 2, 2.2m, "4.2" },
			new object[] { 3, 3.3m, "6.3" },
		};

		# region Setup and Tear Down
		/// <summary>
		/// TestFixtureSetUp called once before any tests have been run in the same TestFixture
		/// </summary>
		[TestFixtureSetUp] public void FixtureSetUp()
    	{
			// Set up code here.
		}
		/// <summary>
		/// TestFixtureTearDown called once after all tests have been run in the same TestFixture
		/// </summary>
    	[TestFixtureTearDown] public void FixtureTearDown()
    	{
			// Clear up code here.
		}

		/// <summary>
		/// SetsUp is called once before each Test within the same TestFxiture
		/// </summary>
		[SetUp] public void SetUp()
    	{
			// Set up code here.
			// If this throws an exception no Test in the TestFixture are run.
		}

		/// <summary>
		/// TearsDown is called once after each Test within the same TestFixture.
		/// </summary>
    	[TearDown] public void TearDown()
    	{
			 // Clear up code here.
			// Will not run if no tess are run due to [SetUp] throwing an exception
		}
		# endregion

		/// <summary>
		/// ExpectedException defines what exception and how it is configured
		/// </summary>
		[Test, ExpectedException( typeof(Exception), ExpectedMessage = "Foo", MatchType = MessageMatch.Exact)]
		public void ExpectedExceptionAttributeTest()
		{
			// MessageMatch is an enum of: Contains, Exact, Regex, StartsWith
			throw new Exception("Foo");
		}

		/// <summary>
		/// Explicit defines tests which are only run manualy.
		/// </summary>
		[Test, Explicit("Test has to be run explicitly")]
    	public void ExplicitAttributeTest()
    	{
		}

		/// <summary>
		/// Ignore marks tests which are not run even if run manually
		/// </summary>
		[Test, Ignore("Ignore this test")]
    	public void IgnoreAttribueTest()
    	{
		}

		/// <summary>
		/// MaxTimeAttribute defines the max run time in milliseconds before the test is considered as failed but allowed to complete.
		/// </summary>
		[Test, MaxTimeAttribute(2000)]
		public void MaxtimeAttributeTest()
		{
		}

		/// <summary>
		/// Timeout defines the max run time in milliseconds before the test is automatically failed.
		/// Can be used on TestFixture to set for each contained Test's
		/// </summary>
		[Test, Timeout(200)]
		public void TimeOutTest()
		{
		}

		/// <summary>
		///
		/// </summary>
		[Test, Platform("Mono"), Culture("en-GB")]
		public void PlatformAttributeTest()
  		{
			// Can also provide exclusion culture and platform
			// Test case is ignored if Platform or Cultrue can not be provided
 		}

		/// <summary>t
		/// Property: categorises the test witin the test output XML.
		/// </summary>
		[Test, Property("PropertyName", "Value")]
		public void PropertyAttributeTest()
    	{}

		/// <summary>
		/// Custom Property: categorises the test within the test output XML.
		/// </summary>
		[Test, CustomPropertyAttribute(CustomPropertyValue.One)]
		public void CustomPropertyAttributeTest()
    	{}

		#region Parameterized
		/// <summary>
		/// Combinatorial: The test is run with each combination of Values for each parameter
		/// </summary>

		[Test, Combinatorial]
		public void CombinatorialAttributeTest ([Values(1,2,3)] int a, [Values("a", "b", "c")] string b)
		{
			// Called 9 times with  parameter pairs of: {1,a}, {1,b}, {1,c}, {2,a}, {3,b}....
		}

		/// <summary>
		/// Random: Test can be run with a random value. Random(Min,Max,Count)
		/// </summary>
		[Test]
		public void RandomAttributeTest(
    	[Random(1, 10, 2)] int value)
		{
			// Called 2 times with a random integer between 1 and 10
			Assert.That(value, Is.InRange(1,10));
		}

		/// <summary>
		/// Sequential: Parameters with values are run in sequence
		/// </summary>
		[Test, Sequential]
		public void SequentialAttributeTest(
    	[Values(1,2,3)] int x,
    	[Values("A","B")] string s)
		{
			// Test runs for parameter pairs {1,A}, {2,B}, {3, null}
		}

		/// <summary>
		/// Range: Parameter is run with a sequence of values incremented. Range(Min,Max,Increment).
		/// </summary>
		[Test]
		public void RangeAttributeTest(
    	[Range(0.0, 1, 0.5)] decimal value)
		{
			// Test run for parameters, 0.0, 0.5, 1.0
			Assert.That(value, Is.InRange(0m,1m));
		}

		/// <summary>
		/// TestCaseSource: referencing a public property which privides a sequence of test data
		/// </summary>
		[Test, TestCaseSource("CaseSourceTestData")]
		public void CaseSourceTest(int a, decimal b, string c)
		{
			// Can also specify the class to which the property is found upon.
			Assert.That(a + b, Is.EqualTo(Decimal.Parse(c)));
		}

		/// <summary>
		/// TestCaseSource: referncing a class and property which provides a sequence of test data and expected output.
		/// </summary>
		[Test,TestCaseSource(typeof(TestCaseDataFactory),"TestCasesDataForTestCaseSourceTest")]
		public decimal TestCaseSourceTest(int a, string b)
		{
			int bInt;
			if( !int.TryParse(b, out bInt))
				throw new ArgumentException(string.Format("Can not parse '{0}' to an integer", b), "b");

			return a + bInt;
		}

		/// <summary>
		/// TestCase: provides a test input data and expected result.
		/// </summary>
		[TestCase(1,1, Result=2)]
		[TestCase(2,2, Result=4)]
		[TestCase(3,3, Result=6)]
		public int TestCaseTest(int a, int b)
		{
		  return( a + b);
		}
		#endregion

		/// <summary>
		/// Assertion Based Test
		/// </summary>
		[Test(), Category("Assertion based testing")]
		public void TestAssertions ()
		{

			// Equality
			Assert.AreEqual (true, true);
			Assert.AreNotEqual (true, false);

			// Identity
			Assert.AreSame (string.Empty, string.Empty);
			Assert.AreNotSame (new object (), new object ());
			Assert.Contains (string.Empty, new List<object> (){string.Empty});

			// Condition
			Assert.IsTrue (true);
			Assert.IsFalse (false);
			Assert.IsNull (null);
			Assert.IsNaN (Double.NaN);
			Assert.IsEmpty (new List<object> ());
			Assert.IsEmpty (new List<object> ());
			Assert.IsNotEmpty (new List<object> (){1});
			Assert.IsNotEmpty ("Foo");

			// Comparision
			Assert.Greater (Decimal.MaxValue, Decimal.MinValue);
			Assert.GreaterOrEqual (Decimal.MinValue, Decimal.MinValue);
			Assert.Less (Decimal.MinValue, Decimal.MaxValue);
			Assert.LessOrEqual (Decimal.MinValue, Decimal.MinValue);

			// Types
			Assert.IsInstanceOf<decimal> (decimal.MinValue);
			Assert.IsNotInstanceOf<int> (decimal.MinValue);
			Assert.IsNotAssignableFrom (typeof(List<Type>), string.Empty);        	// Equivalent to Type.IsAssignableFrom Method
			Assert.IsAssignableFrom (typeof(List<decimal>), new List<decimal> ()); 	// http://msdn.microsoft.com/en-gb/library/system.type.isassignablefrom.aspx
			Assert.IsNotAssignableFrom<List<Type>> (string.Empty);
			Assert.IsAssignableFrom<List<decimal>> (new List<decimal> ());

			// Exceptions
			Assert.Throws (typeof(ArgumentNullException), () => {
				throw new ArgumentNullException (); }
			);

			Assert.Throws<ArgumentNullException> (() => {
				throw new ArgumentNullException (); }
			);

			Assert.DoesNotThrow (() => { });

			Assert.Catch (typeof(Exception), () => {
				throw new ArgumentNullException (); }
			);

			Assert.Catch<Exception> (() => { // Similar as Throws but allows any derrived class of the thrown exception
				throw new ArgumentNullException (); }
			);

			// Strings
			StringAssert.Contains ("Foo", "MooFooMoo");
			StringAssert.StartsWith ("Foo", "FooMoo");
			StringAssert.EndsWith ("Moo", "FooMoo");
			StringAssert.AreEqualIgnoringCase ("FOO", "foo");
			StringAssert.IsMatch ("[0-9]", "1");

			// Collections
			CollectionAssert.AllItemsAreInstancesOfType (new List<decimal> (){ 0m }, typeof(decimal));
			CollectionAssert.AllItemsAreNotNull (new List<decimal> (){ 0m });
			CollectionAssert.AllItemsAreUnique (new List<decimal> (){ 0m, 1m });
			CollectionAssert.AreEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 0m });
			CollectionAssert.AreEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 0m }); // Same as AreEqual though order does not mater
			CollectionAssert.AreNotEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 1m });
			CollectionAssert.AreNotEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 2m });  // Same as AreNotEqual though order does not matter
			CollectionAssert.Contains (new List<decimal> (){ 0m, 1m }, 1m);
			CollectionAssert.DoesNotContain (new List<decimal> (){ 0m, 1m }, 2m);
			CollectionAssert.IsSubsetOf (new List<decimal> (){ 1m }, new List<decimal> (){ 0m, 1m }); // {1} is considered a SubSet of {1,2}
			CollectionAssert.IsNotSubsetOf (new List<decimal> (){ 1m, 2m }, new List<decimal> (){ 0m, 1m });
			CollectionAssert.IsEmpty (new List<decimal> (){ });
			CollectionAssert.IsNotEmpty (new List<decimal> (){ 1m });
			CollectionAssert.IsOrdered (new List<decimal> (){ 1m, 2m, 3m });
			CollectionAssert.IsOrdered (new List<string> (){ "a", "A", "b"}, StringComparer.CurrentCultureIgnoreCase);
			CollectionAssert.IsOrdered (new List<int> (){ 3,2,1}, new ReverseComparer()); // Only supports ICompare and not ICompare<T> as of version 2.6

			//  File Assert: various ways to compare a stream or file.
			FileAssert.AreEqual (new MemoryStream (), new MemoryStream ());
			FileAssert.AreEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile.txt"));
			FileAssert.AreEqual ("MyFile.txt", "MyFile.txt");
			FileAssert.AreNotEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile2.txt"));
			FileAssert.AreNotEqual ("MyFile.txt", "MyFile2.txt");
			FileAssert.AreNotEqual (new FileStream ("MyFile.txt", FileMode.Open), new FileStream ("MyFile2.txt", FileMode.Open));

			// Utilities: will cause the test to stop immediatly and mark the test as:
			Assert.Pass ();
			Assert.Fail ();
			Assert.Ignore ();
			Assert.Inconclusive ();

			// Defining the failed message
			Assert.IsTrue(true, "A failed message here"); // also object[] params can be defined
		}

		/// <summary>
		/// Constraint based testing: Test cases with a fluent design pattern
		/// </summary>
		[Test()]
		[Category("Constraint based testing")]
		public void TestConstraints ()
		{

			// Numerical Equality
			Assert.That (1, Is.EqualTo (1));
			Assert.That (1, Is.Not.EqualTo (2));
			Assert.That (1.1, Is.EqualTo (1.2).Within (0.1)); // Allow a tollerance
			Assert.That (1.1, Is.EqualTo (1.01).Within (10).Percent); // Pass tollerance within percent

			// Float Equality
			Assert.That (20000000000000004.0, Is.EqualTo (20000000000000000.0).Within (1).Ulps); // Pass tollerance with units of last place

			// String Equality
			Assert.That ("Foo!", Is.EqualTo ("Foo!"));
			Assert.That ("Foo!", Is.Not.EqualTo ("FOO!"));
			Assert.That ("Foo!", Is.EqualTo ("FOO!").IgnoreCase);
			Assert.That (new List<string> (){ "FOO!"}, Is.EqualTo (new List<string> (){ "Foo!"}).IgnoreCase);

			// Date, Time and TimeSpan equality
			Assert.That (DateTime.Today, Is.EqualTo (DateTime.Today));
			Assert.That (DateTime.Now, Is.Not.EqualTo (DateTime.Now));
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (TimeSpan.FromSeconds (1))); // Time based pass tollerances
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Days);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Hours);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Minutes);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Seconds);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Milliseconds);

			// Collection equality
			Assert.That (new double[] {1.0,2.0,3.0}, Is.EqualTo (new int[] {1,2,3}));
			Assert.That (new double[] {1.0,2.0,3.0}, Is.Not.EqualTo (new int[] {1,2,3, 4}));
			Assert.That (new double[] {1.0,2.0,3.0,4.0}, Is.EqualTo (new  int[,] {{1,2}, {3,4}}).AsCollection); // Compare data and not collection (flattens a collection of collections)

			// Customer Comparer
			Assert.That( int.MinValue, Is.EqualTo(int.MaxValue).Using(new WhoCaresComparer()));

			// Identity (Same instance of)
			Assert.That( string.Empty, Is.SameAs(string.Empty));
			Assert.That( new object(), Is.Not.SameAs(new object()));

			// Condition
			Assert.That( string.Empty, Is.Not.Null);
			Assert.That( true, Is.True);
			Assert.That( true, Is.Not.False);
			Assert.That( double.NaN, Is.NaN);
			Assert.That( string.Empty, Is.Empty);
			Assert.That( new List<int>(), Is.Empty);
			Assert.That( new List<int>(){1,2,3}, Is.Unique);

			// Comparision
			Assert.That(1, Is.LessThan(2));
			Assert.That(1, Is.GreaterThan(0));
			Assert.That(1, Is.LessThanOrEqualTo(1));
			Assert.That(1, Is.GreaterThanOrEqualTo(1));
			Assert.That(1, Is.AtLeast(0));	// Same as GreaterThanOrEqualTo
			Assert.That(1, Is.AtMost(2)); 	// Same as LessThanOrEqualTo
			Assert.That(1, Is.InRange(1,2));

			// Path: comparision on file path only without comparing the contents.
			// All paths are converted to 'canonical' path before comparing; full direct path to file.
			Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt"));
			Assert.That( "MyFile.txt", Is.SamePath( "MYFILE.TXT" ).IgnoreCase );
			Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt").RespectCase);
			Assert.That( "/usr/bin", Is.SubPath("/usr"));			// directory exists within another
			Assert.That( "/usr/bin", Is.SamePathOrUnder("/usr"));	// SamePath or SubPath

			// Type Constraints
			Assert.That(new MemoryStream(), Is.InstanceOf(typeof(Stream)));  // Is type or ancestor
			Assert.That(new MemoryStream(), Is.TypeOf(typeof(MemoryStream))); // Is type and not ancestor
			Assert.That(new object(), Is.AssignableFrom(typeof(MemoryStream))); // Can be assigned from
			Assert.That(new MemoryStream(), Is.AssignableTo(typeof(Stream))); // Can be assignable to

			Assert.That(new MemoryStream(), Is.InstanceOf<Stream>());  // Is type or ancestor
			Assert.That(new MemoryStream(), Is.TypeOf<MemoryStream>()); // Is type and not ancestor
			Assert.That(new object(), Is.AssignableFrom<MemoryStream>()); // Can be assigned from
			Assert.That(new MemoryStream(), Is.AssignableTo<Stream>()); // Can be assignable to

			// String Comparision
			Assert.That( "Foo", Is.StringContaining( "o" ) );
			Assert.That( "Foo", Is.StringContaining( "O" ).IgnoreCase );
			Assert.That( "Foo", Is.StringStarting( "F" ) );
			Assert.That( "Foo", Is.StringEnding( "o" ) );
			Assert.That( "Foo", Is.StringMatching( "^[F]" ) ); // Regular ecpression match

			// Collection Comparison
			Assert.That( new List<int>(){1,2,3}, Has.All.GreaterThan(0) );
			Assert.That( new List<int>(){1,2,3}, Is.All.GreaterThan(0) );
			Assert.That( new List<int>(){1,2,3}, Has.None.GreaterThan(4));
			Assert.That( new List<int>(){1,2,3}, Has.Some.GreaterThan(2));
			Assert.That( new List<int>(){1,2,3}, Has.Count.EqualTo(3));
			Assert.That( new List<int>(){1,2,3}, Is.Unique);
			Assert.That( new List<int>(){1,2,3}, Has.Member(1));  // Contains
			Assert.That( new List<int>(){1,2,3}, Is.EquivalentTo( new List<int>(){3,2,1})); // Same data without carring about the order
			Assert.That( new List<int>(){1,2,}, Is.SubsetOf( new List<int>(){3,2,1})); // All are cotained.

			// Property Constraint
			Assert.That( new List<int>(), Has.Property("Count").EqualTo(0));  // Checks public property
			Assert.That( new List<int>(), Has.Count.EqualTo(0));			  // Same as Has.Property("Count").EqualTo(0)
			Assert.That( string.Empty, Has.Length.EqualTo(0));				  // Same as Has.Property("Length").EqualTo(0)
			Assert.That ( new Exception("Foo"), Has.Message.EqualTo("Foo"));  // Exception has message
			Assert.That ( new Exception("Foo", new ArgumentException("Moo")), // Inner exception is of type and has message
			             Has.InnerException.InstanceOf<ArgumentException>().And.InnerException.Message.EqualTo("Moo"));

			// Throws Constraint
			// See also Property constrains for Message and Inner Exception
			// Throws.Exception allow AND, Throws.InstanceOf<> is short hand
			Assert.That (() => { throw new ArgumentException("Foo"); },
				Throws.Exception.InstanceOf<ArgumentException>().And.Message.EqualTo("Foo"));

			Assert.That (() => { throw new ArgumentNullException("Foo"); },
				Throws.Exception.TypeOf<ArgumentNullException>());

			Assert.That (() => { throw new ArgumentNullException("Foo"); },
				Throws.InstanceOf<ArgumentNullException>());

			Assert.That (() => { }, Throws.Nothing);

			Assert.That (() => { throw new Exception("Foo", new ArgumentException("Moo"));},
				Throws.Exception.Message.EqualTo("Foo").And.InnerException.InstanceOf<ArgumentException>());

			Assert.That (() => { throw new ArgumentException(); }, Throws.ArgumentException);

			// Compound Constraints
			Assert.That( 2, Is.Not.EqualTo( 1 ));
			Assert.That( new List<int>(){ 1, 2, 3 }, Is.All.GreaterThan( 0 ) );

			Assert.That( 1, Is.GreaterThan( 0 ).And.LessThan( 2 ) );  // .And amd & are the same
			Assert.That( 1, Is.GreaterThan( 0 ) & Is.LessThan( 2 ) );

			Assert.That( 1, Is.LessThan( 10 ) | Is.GreaterThan( 0 ) ); // .Or and | are the same
			Assert.That( 1, Is.LessThan( 10 ).Or.GreaterThan( 0 ) );

			// Delayed
			Assert.That(() => { return true;}, Is.True.After(10));		// Passes after x time
			Assert.That(() => { return true;}, Is.True.After(10, 10));	// Passes after x time and polling..

			// List Mapper
			Assert.That(List.Map(new List<string>(){"1", "22", "333"}).Property("Length"),  // Allows all elememts in a list to have a condition provided for them
			            Is.EqualTo(new List<int>(){1,2,3}));
		}
	}
	# region Elements consumed by the tests above
	public class WhoCaresComparer : IEqualityComparer<int>
	{
	    public bool Equals(int b1, int b2)
	    {
			return true;
	    }

	    public int GetHashCode(int aNumber)
	    {
			return aNumber.GetHashCode();
	    }
	}

	public class ReverseComparer : IComparer
	{
		public int Compare (object a, object b)
		{
			return ((int)b).CompareTo((int)a);
		}
	}

	public enum CustomPropertyValue
	{
    	One,
    	Two,
   	}

	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class CustomPropertyAttribute : PropertyAttribute
	{
    	public CustomPropertyAttribute( CustomPropertyValue value ) : base( "Custom", value.ToString() )
		{
		}
	}
	#endregion
}