Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Created January 20, 2020 07:01
Show Gist options
  • Save gsscoder/f57b6999ff65d02179c5f43184631382 to your computer and use it in GitHub Desktop.
Save gsscoder/f57b6999ff65d02179c5f43184631382 to your computer and use it in GitHub Desktop.
Type extension method to check if an instance is of anonymous type
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
static class TypeExtensions
{
public static Boolean IsAnonymous(this Type type)
{
if (!type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any()) {
return false;
}
var name = type.Name;
if (name.Length < 3) {
return false;
}
return name[0] == '<' &&
name[1] == '>' &&
name.IndexOf("AnonymousType", StringComparison.Ordinal) > 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment