First, in the line "
public AuthAttribute)
", brackets are unbalanced.
Unfortunately, the question makes little to no sense; and something tells me that you won't add much sense when you answer my question I asked you in my comment to the question. However, it wakes up my curiosity. So, let me answer to the question as it is, even without your explanation (which are normally important).
Of course you can use such attribute to mark some methods as having some special property. And of course you can have some instance method of an attribute class and call it from its constructor. But what can it do? Pretty much nothing, if it is a parameterless method. Of course, this is so if you don't misuse the attribute, that is if you use it only to apply to some some declaration, from the level of an assembly to the level of a method parameter and don't instantiate such class in your runtime code directly.
You just need to understand what CLI and CLR do to the attribute. If an attribute is applied to some declaration, even if that declaration is never used in code, for each such declaration, the attribute type is
statically instantiated. By the way, your code sample would be a great answer to the question which are asked from time to time: "Is it possible to write code fragment which is executed before the entry-point method (
Main
)?" Of course it is possible; this would be, for example, your method
Do
! When it happens, nothing in the application is yet called. (By the way, even the
System.Console
is not initialized, so in my example, writing to the console from
Do
screws up the whole output!) Your methods
ShowA
and
ShowB
are not yet called, moreover, your attribute instance "knows" nothing about them. If you thought that you can control access to these method, it would be quite a naive thought.
This is the reason why non-constructor methods of attribute types are rarely used: there is just not enough work for them. In your example, it is also useless. :-)
But what code can "know" about these methods and attributes applied to them? Of course, this is
reflection. That said, you can affect the use of your
ShowA
and
ShowB
only if they are called not directly, but through reflection, more exactly, through one of the
System.Reflection.MethodInfo.Invoke
methods:
https://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.invoke%28v=vs.110%29.aspx[
^].
During runtime, you can obtain the instances of
System.Reflection.MethodInfo
and apply one of the reflection's
GetCustomAttribute
methods. This way, you can figure out if your attribute is applied to this method and then decide if you want to invoke the method or not, in what order, with what parameters, and so on. The whole chain starts from the type
System.Type
, in your case, obtained from the type
TauthTest
or its instance. This chain can be relatively long, but extremely trivial; you only need to look at the MSDN documentation on the reflection types you face down the road.
That's all.
—SA