pass a null as a one param argument
I have a method that accepts params
as a parameter to check if a property has invalid value or not. If the property has an invalid value, it throws an exception
private void ShouldNotEqual<T>(Expression<Func<Ticket, T>> outExpr, params object[] notValidPropertyValue)
The usage is:
ShouldNotEqual(student => student.Name, "jack", string.Empty);
ShouldNotEqual(student => student.Address, string.Empty, null);
The problem with this implementation is when I want to check a property against null
, the parameter notValidPropertyValue
is set as null, not an array with one element whose value is equal to null
.
// I need to use it in this way
ShouldNotEqual(student => student.Phone, null); // Throws NullReferenceException for notValidPropertyValue
How can I fix it?
Solution 1:
Explicitly pass an object[]
:
ShouldNotEqual(student => student.Phone, new object[] { null });
Or add an overload to prevent this happening:
private void ShouldNotEqual<T>(
Expression<Func<Ticket, T>> outExpr,
object notValidPropertyValue)
{
ShouldNotEqual(outExpr, new object[] { notValidPropertyValue });
}
This will take precedence when a single object, or null
is passed.
Solution 2:
Are you sure you want null
in the array and not just an empty array?
If you want null
, use
var array = new object[] { null };
to create an array containing one value, null
.
Then call ShouldNotEqual
with the array, e.g.
ShouldNotEqual(student => student.Phone, array);
Or just inline it:
ShouldNotEqual(student => student.Phone, new object[] { null });
If you want an empty array, then just use
ShouldNotEqual(student => student.Phone, new object[0]);