Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Understanding C# Class and Member Modifiers
By Peter Aitken

Rate This Article: Add This Article To:

Understanding C# Class and Member Modifiers - ' When to Use New '
( Page 2 of 2 )

The New Modifier

The New keyword is usually seen as an operator that is used to create new objects. It also plays a role as a modifier in class definitions and has a totally different meaning. It is used when you want a member of a derived class to hide a member of the same name in the base class. For example, here's a simple class:

public class A
{
            public int total;
}

Suppose you want to derive a new class from A and give it a member called total that is type float. Here's where you need to use the new modifier:

public class B:A
{
            new float total;
}

You don't see new used very often, for two reasons. First of all, omitting new does not prevent compilation; it just results in a warning. The class works as if you had included new — that is, the member in the derived class hides the same-name member in the base class. It can be included as an indication, perhaps to some maintenance programmer down the road, that you really did mean to include the member in the derived class even though the base class already had one of that name. Second, it is usually preferred to explicitly override the base class member using the override keyword.

I hope that this brief exposition has helped you to understand all these keywords and their uses. For convenience I have summarized this information in the following table and included the Visual Basic counterparts for each of the C# keywords.

C#

VB

Class cannot be inherited (cannot be a base class).

Sealed

NotInheritable

Class cannot be instantiated but only used as based class and/or with abstract methods.

Abstract

MustInherit

For class members: member is accessible only from the class in which it is declared. For classes: only allowed on nested classes to restrict access to the nested class to the containing class..

Private

Private

For class members: member is accessible only from types defined in the same assembly. For classes: class is accessible only from types in the same assembly.

Internal

Friend

For members: member is accessible from the class in which it is declared and from any class derived from that class.

Protected

Protected

Combines the access of Protected and Internal for a class member

Protected Internal

Protected Friend

Access is not restricted.

Public

Public

Hides a member inherited from a base class.

New

Shadows



 
 
>>> More ASP and .Net Coding Techniques Articles          >>> More By Peter Aitken