I’m trying to do cast a List to an IEnumerable, so I can verify that different lists are not null or empty:
Suppose myList is a List < T > . Then in the caller code I wanted:
Validator.VerifyNotNullOrEmpty(myList as IEnumerable<object>,
@"myList",
@"ClassName.MethodName");
The valdiating code would be:
public static void VerifyNotNullOrEmpty(IEnumerable<object> theIEnumerable,
string theIEnumerableName,
string theVerifyingPosition)
{
string errMsg = theVerifyingPosition + " " + theIEnumerableName;
if (theIEnumerable == null)
{
errMsg += @" is null";
Debug.Assert(false);
throw new ApplicationException(errMsg);
}
else if (theIEnumerable.Count() == 0)
{
errMsg += @" is empty";
Debug.Assert(false);
throw new ApplicationException(errMsg);
}
}
However, this doens’t work. It compiles, but theIEnumerable is null! Why?
IEnumerable<object>is not a supertype ofIEnumerable<T>, so it is not a supertype ofList<T>either. See question 2575363 for a brief overview of why this is the case (it’s about Java, but the concepts are the same). This problem has been solved in C# 4.0, by the way, which supports covariant generics.The reason why you didn’t find this error is because you used
x as T, where you should have been using a normal cast ((T)x), see question 2139798. The resultingInvalidCastExceptionwould have pointed you at your error. (In fact, if the type relationship were correct (i.e. ifIEnumerable<object>were a supertype ofList<T>), you wouldn’t need a cast at all.)To solve your problem, make your method generic, so that it accepts an
IEnumerable<T>instead of anIEnumerable<object>, and skip the cast completely.