While writing this method for a custom NUnit Constraint.
private void AddMatchFailure(string failureName, TExpected expected, TActu
What are the rules when comparing a ValueType to null and how should I write the method to account for that without limiting the generic parameters by adding a class constraint?
If you do not know that they will be reference types, then you can say
private void AddMatchFailure(
string failureName,
TExpected expected,
TActual actual
) {
_matchFailures.Add(
String.Format(MatchFailureFormat, failureName,
IsDefault(expected) ? DefaultStringForType() : expected.ToString(),
IsDefault(actual) ? DefaultStringForType() : actual.ToString()
);
}
private bool IsDefault(T value) {
if(typeof(T).IsValueType) {
return default(T).Equals(value);
}
else {
return Object.Equals(null, value);
}
}
private string DefaultStringForType() {
if(typeof(T).IsValueType) {
return default(T).ToString();
}
else {
return "null";
}
}