Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether a Type is an Anonymous Type [duplicate]

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

like image 893
xyz Avatar asked Oct 30 '09 15:10

xyz


People also ask

What is the difference between anonymous type and regular type?

The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

How do you define anonymous type?

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.

What is an anonymous type in C?

What Are Anonymous Types in C#? Anonymous types are class-level reference types that don't have a name. They allow us to instantiate an object without explicitly defining a type. They contain one or more read-only properties. The compiler determines the type of the properties based on the assigned values.

What are difference between anonymous and dynamic types?

Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler. Anonymous type is directly derived from System.


1 Answers

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

like image 112
Ricardo Lacerda Castelo Branco Avatar answered Oct 05 '22 03:10

Ricardo Lacerda Castelo Branco