How is it possible?
namespace test
{
class Attr:Attribute
{
public Attr(int e)
{
}
}
[Attr(E)]
class Test
{
private const int E = 0;
}
}
Doesn't it violate encapsulation principle?
No, this doesn't violate encapsulation. The attribute declaration is logically part of the class. Attr
is not accessing Test.E
(it can't), you are calling the constructor of Attr
with E
from within Test
. This is just as fine as if you were initializing a member.
The C# syntax may make it look like the attribute is "outside" the class somehow, but this is not the case. The IL produced for this class is this:
.class private auto ansi beforefieldinit test.Test
extends [mscorlib]System.Object
{
.custom instance void test.Attr::.ctor(int32) = (
01 00 00 00 00 00 00 00
)
// Fields
.field private static literal int32 E = int32(0)
...
} // end of class test.Test
Had C# adopted a similar syntax, it might have looked something like this:
class Test
{
attribute Attr(E);
private const int E = 0;
}
This would have emphasized the scope of the declaration, but it arguably wouldn't have been as clear. It becomes even less clear when attributes are applied to members (in IL, these directly follow the declaration).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With