Created
June 24, 2011 19:39
-
-
Save thecodejunkie/1045511 to your computer and use it in GitHub Desktop.
Detecting anonymous types on Mono
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Reflection; | |
using System.Runtime.CompilerServices; | |
/// <summary> | |
/// Contains miscellaneous extension methods. | |
/// </summary> | |
public static class Extensions | |
{ | |
/// <summary> | |
/// Checks if the evaluated instance is an anonymous | |
/// </summary> | |
/// <param name="source">The object instance to check.</param> | |
/// <returns><see langword="true"/> if the object is an anonymous type; otherwise <see langword="false"/>.</returns> | |
public static bool IsAnonymousType(this object source) | |
{ | |
if (source == null) | |
{ | |
return false; | |
} | |
var type = source.GetType(); | |
return type.IsGenericType | |
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic | |
&& (type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase) || type.Name.StartsWith("VB$", StringComparison.OrdinalIgnoreCase)) | |
&& (type.Name.Contains("AnonymousType") || type.Name.Contains("AnonType")) | |
&& Attribute.IsDefined(type, typeof (CompilerGeneratedAttribute), false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment