I have a bunch of regular, closed and opened types in my assembly. I have a query that I'm trying to rule out the open types from it
class Foo { } // a regular type
class Bar<T, U> { } // an open type
class Moo : Bar<int, string> { } // a closed type
var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => ???);
types.Foreach(t => ConsoleWriteLine(t.Name)); // should *not* output "Bar`2"
Upon debugging the generic arguments of an open type, I found that their FullName
is null (as well as other things like the DeclaringMethod
) - So this could be one way:
bool IsOpenType(Type type)
{
if (!type.IsGenericType)
return false;
var args = type.GetGenericArguments();
return args[0].FullName == null;
}
Console.WriteLine(IsOpenType(typeof(Bar<,>))); // true
Console.WriteLine(IsOpenType(typeof(Bar<int, string>))); // false
Is there a built-in way to know if a type is open? if not, is there a better way to do it? Thanks.
IsGenericType
?Use the ContainsGenericParameters property to determine whether a Type object represents an open constructed type or a closed constructed type.
– FirenewContainsGenericParameters
pop in the intellisense but I thought it returns true if there are any generic arguments for the type. Doesn't seem so reading the doc - seems that 'argument' is not the same as 'parameter'? @Blackington no, the opposite, filter them out :) – Syrup