Determining whether a Type is an Anonymous Type [duplicate]
Asked Answered
M

6

27

In C# 3.0, is it possible to determine whether an instance of Type represents an Anonymous Type?

Malfunction answered 30/10, 2009 at 15:58 Comment(1)
D
40

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).

Dybbuk answered 30/10, 2009 at 16:28 Comment(5)
@Philip but not fool-proof, see this question.Dialogue
@MattWarren, which question?Mclaurin
on mono this type.FullName.Contains("AnonymousType"); isn't true.Zorine
FYI - this doesn't work if you're checking the type from within a generic class or functionPairoar
Clarification: this doesn't work if you're checking a type param in a generic class/method. check the actual instance of an object's .GetType() result insteadPairoar
M
20

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.

Monophthong answered 27/9, 2011 at 15:12 Comment(7)
Thanks, opting for the return type.NameSpace == null; improved my programs' processing by almost 50% (was using this approach: #2483523)Avocado
Yeah. This should be the correct answer. I don't think any reasonable concrete class would ever have a null namespace.Cube
+1 thanks! Leaving here my comment in order to favorite this answer (not just a thread)Mclaurin
I think global classes can have namespace == null; so that check alone wont be enough. @AvocadoRelate
@Relate C# has no concept (VB.NET does, as do possibly more, but if restricting to a language).Tectonic
@Tectonic C# does have the concept of null namespace classes. Try a class without namespace around it..Relate
Dont you think you can perfectly have all these conditions met for a named type as well? This answer looks incorrect.Relate
C
6

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;
}
Corfam answered 30/10, 2009 at 16:42 Comment(0)
X
2

In methadata and CLR there is no such terms as anonymous types. Anonymous types are solely compiler feature.

Xanthus answered 30/10, 2009 at 16:0 Comment(0)
E
1

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.

Evening answered 30/10, 2009 at 16:18 Comment(3)
Don't worry about why. It is curiosity :)Malfunction
I thought the same thing, but it's a bit dirty. What if they change the name in c#5? Any code that uses it will be broken.Fictive
It's important to ask and explain "why" 'cause often there are other possible answers which may not be evident from the question without knowing more.Subjacent
Z
1

It seems anonymous types get a DebuggerDisplayAttribute put on them where Type = "<Anonymous Type>".

Edit: But only when you compile in Debug mode. Darn.

Zennie answered 30/10, 2009 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.