I have the following method which takes a Type as a parameter and checks if it is IEnumerable<T>. If it is, it returns true and sets the type of T in an out variable, otherwise it returns false.
private static bool TryGetEnumeratedType(Type type, [NotNullWhen(true)] out Type? enumeratedType)
{
enumeratedType = null;
bool isEnumerable = type.GetInterfaces().Any(i => i.GetTypeInfo() == typeof(IEnumerable));
if (!isEnumerable)
{
return false;
}
Type? genericType = type.GetGenericArguments().FirstOrDefault();
if (genericType is null)
{
return false;
}
enumeratedType = genericType;
return true;
}
If I call the method this way, there is no issue:
Type fieldType;
if (TryGetEnumeratedType(inType, out Type? type))
{
fieldType = type;
}
else
{
fieldType = inType;
}
But if I assign the result to a variable and check against the variable, I get a compiler warning when assigning fieldType = type saying that type may be null.
Type fieldType;
bool isEnumerable = TryGetEnumeratedType(inType, out Type? type);
if (isEnumerable)
{
fieldType = type;
}
else
{
fieldType = inType;
}
Is this a bug, or am I missing something?