15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Modifiers ❘ 99<br />

modifiers<br />

You have already encountered quite a number of so-called modifiers — keywords that can be applied to a<br />

type or to a member. Modifiers can indicate the visibility of a method, such as public or private, or the<br />

nature of an item, such as whether a method is virtual or abstract. <strong>C#</strong> has a number of modifiers, <strong>and</strong> at<br />

this point it’s worth taking a minute to provide the complete list.<br />

Visibility modifiers<br />

Visibility modifiers indicate which other code items can view an item.<br />

modifier OPPlies To desCriPTion<br />

public Any types or members The item is visible to any other code.<br />

protected<br />

internal<br />

Any member of a type, also any<br />

nested type<br />

Any member of a type, also any<br />

nested type<br />

The item is visible only to any derived type.<br />

The item is visible only within its containing<br />

assembly.<br />

private Any types or members The item is visible only inside the type to<br />

which it belongs.<br />

protected internal<br />

Any member of a type, also any<br />

nested type<br />

The item is visible to any code within its containing<br />

assembly <strong>and</strong> also to any code inside<br />

a derived type.<br />

Note that type definitions can be internal or public, depending on whether you want the type to be visible<br />

outside its containing assembly.<br />

public class MyClass<br />

{<br />

// etc.<br />

You cannot define types as protected, private, or protected internal because these visibility levels would be<br />

meaningless for a type contained in a namespace. Hence, these visibilities can be applied only to members.<br />

However, you can define nested types (that is, types contained within other types) with these visibilities<br />

because in this case the type also has the status of a member. Hence, the following code is correct:<br />

public class OuterClass<br />

{<br />

protected class InnerClass<br />

{<br />

// etc.<br />

}<br />

// etc.<br />

}<br />

If you have a nested type, the inner type is always able to see all members of the outer type. Therefore, with<br />

the preceding code, any code inside InnerClass always has access to all members of OuterClass, even<br />

where those members are private.<br />

other modifiers<br />

The modifiers in the following table can be applied to members of types <strong>and</strong> have various uses. A few of<br />

these modifiers also make sense when applied to types.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!