Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 574893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T13:52:48+00:00 2026-05-13T13:52:48+00:00

I’m creating a custom attribute in C# and I want to do different things

  • 0

I’m creating a custom attribute in C# and I want to do different things based on whether the attribute is applied to a method versus a property. At first I was going to do new StackTrace().GetFrame(1).GetMethod() in my custom attribute constructor to see what method called the attribute constructor, but now I’m unsure what that will give me. What if the attribute was applied to a property? Would GetMethod() return a MethodBase instance for that property? Is there a different way of getting the member to which an attribute was applied in C#?

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property,
    AllowMultiple = true)]
public class MyCustomAttribute : Attribute

Update: okay, I might have been asking the wrong question. From within a custom attribute class, how do I get the member (or the class containing the member) to which my custom attribute was applied? Aaronaught suggested against walking up the stack to find the class member to which my attribute was applied, but how else would I get this information from within the constructor of my attribute?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T13:52:48+00:00Added an answer on May 13, 2026 at 1:52 pm

    Since there seems to be a lot of confusion with respect to how the stack frames and methods work, here is a simple demonstration:

    static void Main(string[] args)
    {
        MyClass c = new MyClass();
        c.Name = "MyTest";
        Console.ReadLine();
    }
    
    class MyClass
    {
        private string name;
    
        void TestMethod()
        {
            StackTrace st = new StackTrace();
            StackFrame currentFrame = st.GetFrame(1);
            MethodBase method = currentFrame.GetMethod();
            Console.WriteLine(method.Name);
        }
    
        public string Name
        {
            get { return name; }
            set
            {
                TestMethod();
                name = value;
            }
        }
    }
    

    The output of this program will be:

    set_Name

    Properties in C# are a form of syntactic sugar. They compile down to getter and setter methods in the IL, and it’s possible that some .NET languages might not even recognize them as properties – property resolution is done entirely by convention, there aren’t really any rules in the IL spec.

    Now, let’s say for the moment that you had a really good reason for a program to want to examine its own stack (and there are precious few practical reasons to do so). Why in the world would you want it to behave differently for properties and methods?

    The whole rationale behind attributes is that they are a kind of metadata. If you want a different behaviour, code it into the attribute. If an attribute can mean two different things depending on whether it’s applied to a method or property – then you should have two attributes. Set the target on the first to AttributeTargets.Method and the second to AttributeTargets.Property. Simple.

    But once again, walking your own stack to pick up some attributes from the calling method is dangerous at best. In a way, you are freezing your program’s design, making it far more difficult for anybody to extend or refactor. This is not the way attributes are normally used. A more appropriate example, would be something like a validation attribute:

    public class Customer
    {
        [Required]
        public string Name { get; set; }
    }
    

    Then your validator code, which knows nothing about the actual entity being passed in, can do this:

    public void Validate(object o)
    {
        Type t = o.GetType();
        foreach (var prop in
            t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            if (Attribute.IsDefined(prop, typeof(RequiredAttribute)))
            {
                object value = prop.GetValue(o, null);
                if (value == null)
                    throw new RequiredFieldException(prop.Name);
            }
        }
    }
    

    In other words, you’re examining the attributes of an instance that was given to you but which you don’t necessarily know anything about the type of. XML attributes, Data Contract attributes, even Attribute attributes – almost all attributes in the .NET Framework are used this way, to implement some functionality that is dynamic with respect to the type of an instance but not with respect to the state of the program or what happens to be on the stack. It is very unlikely that you are actually in control of this at the point where you create the stack trace.

    So I’m going to recommend again that you don’t use the stack-walking approach unless you have an extremely good reason to do so which you haven’t told us about yet. Otherwise you are likely to find yourself in a world of hurt.

    If you absolutely must (don’t say we didn’t warn you), then use two attributes, one that can apply to methods and one that can apply to properties. I think you’ll find that to be much easier to work with than a single super-attribute.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
i want to parse a xhtml file and display in UITableView. what is the
I want to construct a data frame in an Rcpp function, but when I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.