views:

246

answers:

5

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

+1  A: 

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

Vitaliy Liptchinsky
+1  A: 

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.

jlew
Don't worry about why. It is curiosity :)
frou
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.
Philip Wallace
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.
Sam
A: 

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

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

Tinister
In release build too?
Philip Wallace
+8  A: 

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

Ricardo Lacerda Castelo Branco
+ 1 Nice answer.
Philip Wallace
@Philip but not fool-proof, see this question.
Matt Warren
+2  A: 

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;
}
JaredPar