In C# 3.0, is it possible to determine whether an instance of Type
represents an Anonymous Type?
Even though an anonymous type is an ordinary type, you can use some heuristics:
public static class TypeExtension {
public static Boolean IsAnonymousType(this Type type) {
Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Count() > 0;
Boolean nameContainsAnonymousType = type.FullName.Contains("AnonymousType");
Boolean isAnonymousType = hasCompilerGeneratedAttribute && nameContainsAnonymousType;
return isAnonymousType;
}
}
Another good heuristic to be used is if the class name is a valid C# name (anonymous type are generated with no valid C# class names - use regular expression for this).
type.FullName.Contains("AnonymousType");
isn't true. –
Zorine Properties of an anonymous typed object
- has a namespace equal to null
- base type of System.Object
- IsSealed = true
- custom attribute 0 is DebuggerDisplayAttribute, Type: ""
- IsPublic = false
For my particular application, if the namespace is null it can be inferred that the type is anonymous, so checking that the namespace is null is probably the least expensive check.
There is no C# language construct which allows you to say "Is this an anonymous type". You can use a simple heuristic to approximate if a type is an anonymous type, but it's possible to get tricked by people hand coding IL, or using a language where such characters as > and < are valid in identifiers.
public static class TypeExtensions {
public static bool IsAnonymousType(this Type t) {
var name = t.Name;
if ( name.Length < 3 ) {
return false;
}
return name[0] == '<'
&& name[1] == '>'
&& name.IndexOf("AnonymousType", StringComparison.Ordinal) > 0;
}
In methadata and CLR there is no such terms as anonymous types. Anonymous types are solely compiler feature.
Might be helpful to know why you want to know this. If you execute the following:
var myType = new { Name = "Bill" };
Console.Write( myType.GetType().Name );
...you would see something like "<>f__AnonymousType0`1" output as the type name. Depending on your requirements, you may be able to assume that a type starting with <>, containing "AnonymousType" and a back quote character is what you're looking for.
It seems anonymous types get a DebuggerDisplayAttribute
put on them where Type = "<Anonymous Type>"
.
Edit: But only when you compile in Debug mode. Darn.
© 2022 - 2024 — McMap. All rights reserved.