Thursday, April 26, 2012

Private const

Some odd attribute defining behavior.

Let's define a class with some constants:

class Foo

{
       public const string String = "some string";
       protected const Type Type = null;
       private const int Int = 42;
}

It's strange but you can access these constants in attribute definition, even protected and public, even without class name specialized!

[MyAttribute(String, Int, Type)]
class Foo
{
       public const string String = "some string";
       protected const Type Type = null;
       private const int Int = 42;
}

class MyAttribute :Attribute
{
       public MyAttribute(string someString, int someInt, Type someType)
       {             
       }
}

Note, that Type constant could be set to null only, because constant initializer must be compiler-time constant and even typeof(Foo) is not a compile-time constant. But it is possible to use typeof(Fooin attribute definition:


[MyAttribute(StringInt typeof(Foo))]
class Foo
{
       public const string String = "some string";
       protected const Type Type = null;
       private const int Int = 42;
}


No comments:

Post a Comment