[C#] How to Determine if a Property Has a Specific Attribute (IsDefined Method)

Using the C# “Attribute” feature allows you to add metadata (such as maximum character length, required fields, or database column names) to classes or properties.

To check whether these attributes are attached to a specific property at runtime, use the IsDefined method from Reflection. This technique is often used when building custom validation libraries or O/R mappers.

目次

Implementation to Check for Attributes

The sample code below checks whether the MaxLengthAttribute (maximum length constraint) is applied to the Name property of the Product class.

Sample Code

using System;
using System.ComponentModel.DataAnnotations; // Namespace for using attributes
using System.Reflection;

public class Program
{
    public static void Main()
    {
        // 1. Get target type information
        Type type = typeof(Product);

        // 2. Get property information to investigate
        PropertyInfo prop = type.GetProperty("Name");

        if (prop != null)
        {
            // 3. Determine if the specified attribute is applied
            // 1st Arg: Attribute Type
            // 2nd Arg: Whether to search inheritance (true/false)
            bool isDefined = prop.IsDefined(typeof(MaxLengthAttribute), inherit: true);

            if (isDefined)
            {
                Console.WriteLine($"Property '{prop.Name}' has MaxLengthAttribute applied.");
            }
            else
            {
                Console.WriteLine($"Property '{prop.Name}' does not have MaxLengthAttribute applied.");
            }

            // (Ref) Checking a property without the attribute
            PropertyInfo priceProp = type.GetProperty("UnitPrice");
            if (!priceProp.IsDefined(typeof(MaxLengthAttribute), inherit: true))
            {
                Console.WriteLine($"Property '{priceProp.Name}' does not have MaxLengthAttribute applied.");
            }
        }
    }
}

// Sample Class
public class Product
{
    // Apply MaxLength attribute
    [MaxLength(100)]
    public string Name { get; set; }

    // No attribute
    public int UnitPrice { get; set; }
}

Execution Result

Property 'Name' has MaxLengthAttribute applied.
Property 'UnitPrice' does not have MaxLengthAttribute applied.

Explanation and Technical Points

1. IsDefined Method

This method is defined in MemberInfo (the parent class of PropertyInfo). It returns true or false indicating if the specified attribute type is applied to that member.

  • Syntax: bool IsDefined(Type attributeType, bool inherit)
  • inherit argument: If true, it searches attributes defined in parent classes as well (if the attribute is inheritable). It is generally recommended to specify true.

2. Distinction from GetCustomAttribute

If you want to retrieve the value set in the attribute (like 100 in the example) in addition to checking for its existence, use the GetCustomAttribute method instead of IsDefined.

  • IsDefined: Use this when you want a fast check just to see “if it is attached.”
  • GetCustomAttribute: Use this when you need to get the attribute instance and read its property values.

3. Prerequisites

To use standard attributes like [MaxLength], the System.ComponentModel.DataAnnotations assembly must be included in your project references (this is usually available by default in modern .NET environments).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次