General list <T> as IEnumerable <object>
I am trying to make a List in 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 validation code will 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 does not work. It compiles, but theIEnumerable is null! Why?
+3
3 answers
IEnumerable<object> IEnumerable<T>, List<T>. . 2575363 , ( Java, ). # 4.0, , .
, , , x as T, ((T)x), . 2139798. InvalidCastException . ( , (.. IEnumerable<object> List<T>), .)
, , IEnumerable<T> IEnumerable<object> .
public static void VerifyNotNullOrEmpty<T>(IEnumerable<T> theIEnumerable,
string theIEnumerableName,
string theVerifyingPosition) { ... }
+5
List IEnumerable, , , , :
public static void VerifyNotNullOrEmpty<T>(this IEnumerable<T> 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);
}
}
:
var myList = new List<string>
{
"Test1",
"Test2"
};
myList.VerifyNotNullOrEmpty("myList", "My position");
:
public static void VerifyNotNullOrEmpty<T>(this IEnumerable<T> items,
string name,
string verifyingPosition)
{
if (items== null)
{
Debug.Assert(false);
throw new NullReferenceException(string.Format("{0} {1} is null.", verifyingPosition, name));
}
else if ( !items.Any() )
{
Debug.Assert(false);
// you probably want to use a better (custom?) exception than this - EmptyEnumerableException or similar?
throw new ApplicationException(string.Format("{0} {1} is empty.", verifyingPosition, name));
}
}
+6