There's nothing out of the box, but I use an extension method to do this:
public static class GenericExtensions
{
/// <summary>
/// Throws an ArgumentNullException if "this" value is default(T)
/// </summary>
/// <typeparam name="T">(Inferred) "this" type</typeparam>
/// <param name="self">"this" value</param>
/// <param name="variableName">Name of the variable</param>
/// <returns>"this" value</returns>
/// <exception cref="System.ArgumentException">Thrown if "this" value is default(T)</exception>
public static T ThrowIfDefault<T>(this T self, string variableName)
{
if (EqualityComparer<T>.Default.Equals(self, default(T)))
throw new ArgumentException(string.Format("'{0}' cannot be default(T)", variableName));
return self;
} // eo ThrowIfDefault<T>
}
Usage:
public void SomeFunc(string value)
{
value.ThrowIfDefault("value");
}
public void MyFunc(Guid guid)
{
guid.ThrowIfDefault("guid");
}
It's also useful in class constructors as it returns the value also:
public class A
{
}
public class B
{
private readonly A _a;
public B(A a)
{
_a = a.ThrowIfDefault("a");
}
}
It is also trivial to write one for strings that ensure that not only is it non-null, but that it also has a length,.