Tuesday, 7 February 2012

C# Compare default(T) values

[TestFixture]
public class TestDefaultValue
{
	[Test]
	public void Test()
	{
		Assert.IsTrue(Helper<string>.IsDefault(default(string)));            
		Assert.IsTrue(Helper<string>.IsDefault(null));
		Assert.IsFalse(Helper<string>.IsDefault(""));
		Assert.IsFalse(Helper<string>.IsDefault("hello"));
	}        
}
public class Helper<T>
{
	public static bool IsDefault(T value)
	{
		if (EqualityComparer<T>.Default.Equals(value, default(T)))
		{
			return true;
		}
		return false;
	}
}

No comments:

Post a Comment