Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created June 24, 2011 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thecodejunkie/1045511 to your computer and use it in GitHub Desktop.
Save thecodejunkie/1045511 to your computer and use it in GitHub Desktop.
Detecting anonymous types on Mono
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