How to check if type is a record

Viewed 1065

Is it possible to check a type is a record?

class Program
{
    static void Main(string[] args)
    {
        IsRecord(typeof(Person)); // true
    }

    static bool IsRecord(Type type)
    {
        // ...
    }
}

public record Person
{
    public string LastName { get; }
    public string FirstName { get; }

    public Person(string first, string last) => (FirstName, LastName) = (first, last);
}
1 Answers

This is just based on a quick look at the compiled code with C# 9. There may be a more official way of determining this. But with what I'm seeing, record types define a public method named <Clone>$ which is otherwise not a valid C# identifier, so if a type has that method the type is a record, barring some other tool able to rewrite the IL using that same name.

var t = typeof(Person);
var isRecord = t.GetMethods().Any(m => m.Name == "<Clone>$");
Related