1

I have a method that I want to check before it runs that each class and interface that has a specific attribute run the method for them and not run for other classes. How do I set this condition?

Maryam
  • 19
  • 2
  • hi, interesting, perhaps might be of interest https://stackoverflow.com/questions/2051065/check-if-property-has-attribute – IronMan Feb 28 '21 at 05:52
  • It couldnt help me – Maryam Feb 28 '21 at 06:30
  • You mean the caller of the method should have specific attribute in order to be able to call the method? Example... if let say `Class1` does not have specific attribute it can not call `MethodX` from `Class2`? is that your requirement? – Chetan Feb 28 '21 at 06:45
  • Exactly. its that I wanted . – Maryam Feb 28 '21 at 07:19
  • See duplicate for how to inspect a class to check for a specific attribute. You still have the problem of verifying that the _caller_ is from a class with that attribute. That information is available only via a stack trace, and a stack trace is a very expensive object to obtain at runtime. I question the wisdom of this approach. Seems like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. You should post a different question explaining what broader problem you are trying to solve, so that you can get an answer that's actually useful and practical. – Peter Duniho Feb 28 '21 at 07:45

1 Answers1

0

You can use this way, first create a class with your specific attribute (I use SerializableAttribute):

    [Serializable]
    public class Sample
    {
        public string Name { get; set; }
    }

And create method to do some thing just if class have specific attribute:

   public void SampleMethod<T>() where T : class
        {
            //skip if class has not your attribute
            if (typeof(T).GetCustomAttribute(typeof(SerializableAttribute)) == null)
                return;

            //do other stuff
        }

Call method like this:

SampleMethod<Sample>();
Dharman
  • 30,962
  • 25
  • 85
  • 135
sa-es-ir
  • 3,722
  • 2
  • 13
  • 31
  • The above doesn't check anything about the caller. It just checks something about the type the caller gave the method. Code in `Class2` without the required attribute can just call the method with `Class1`, that does have the attribute, as the type parameter for the method. This doesn't solve the problem the question's author says they want solved. – Peter Duniho Feb 28 '21 at 07:43