0

So System.Type has an instance method called Attributes.

public TypeAttributes Attributes { get; }

which returns an enum of type TypeAttributes. Here are some members of this enum:

public enum TypeAttributes {
    AnsiClass = 0,
    Class = 0,
    AutoLayout = 0,
    NotPublic = 0,
    Public = 1,
    NestedPublic = 2,
    NestedPrivate = 3,
    NestedFamily = 4,
    NestedAssembly = 5,
    NestedFamANDAssem = 6,
    VisibilityMask = 7,
    NestedFamORAssem = 7,
    SequentialLayout = 8,
    ExplicitLayout = 16,
    LayoutMask = 24,
...
}

But on the other hand, Type class has provides too many properties for most of the stuff appear in this enum:

  • IsPublic
  • IsClass
  • IsNestedFamANDAssem
  • IsAutoLayout
  • ...

So what exactly Type.Attributes is for? I guess it is not a bitmasked value, since it is an enum and it returns only a single member of enum. And this is not a static property on Type class,so what exactly does it do?

ahmet alp balkan
  • 42,679
  • 38
  • 138
  • 214

3 Answers3

2

I guess it is not a bitmasked value

You guess wrong. It's marked as FlagsAttribute:

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

As you indicate, many of these are also available as properties. So, why is it exposed? Well, firstly, because it's the natural representation of this information. The properties (e.g. IsPublic) just hide the bit testing for you. And secondly, sometimes it's a more convenient value to pass around than an array of booleans.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
2

Type.Attributes is a bitmasked value. It even says so in the documentation.

enums are commonly used as Flag data types by decorating them with the Flags attribute.

And those properties of Type, like IsPublic, IsClass etc. just check those flags and return a boolean value. You can see it yourself by looking at the definitions using reflector.

IsPublic, for example does something like this:

public bool IsPublic {
    get {
        return ((this.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public);
    }
}

Not all properties of Type necessarily represent one of the flags though (like IsEnum).

Botz3000
  • 39,020
  • 8
  • 103
  • 127
1

It is bitmasked value where portions of the value represent partiular properties of the Type -

  • myType.Attributes & TypeAttributes.VisibilityMask gives you one of several Public/NonPublic/NestedPublic... values from the enum
  • myType.Attributes & TypeAttributes.LayoutMask gives you layout type (Sequential/Explicit/default)

and so on.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179