Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is possible to access private const field from attribute?

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?

like image 663
Vahe Avatar asked May 29 '17 09:05

Vahe


1 Answers

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).

like image 132
Jeroen Mostert Avatar answered Nov 17 '22 16:11

Jeroen Mostert