Wednesday, 27 November 2013

Shadowing or Member Hiding in C#.NET

 

Shadowing is a useful tool for customizing classes when you want to keep some properties hidden from a third party, but allow your own developers access to specific regions of an inherited class. 

The main purpose of shadowing is to protect the definition of your class members. The base class might undergo a change that creates an element with the same name as one you have already defined. If this happens, the Shadows modifier forces references through your class to be resolved to the member you defined, instead of to the new base class element.

 

Types of Shadowing

An element can shadow another element in two different ways. The shadowing element can be declared inside a sub region of the region containing the shadowed element, in which case the shadowing is accomplished through scope. Or a deriving class can redefine a member of a base class, in which case the shadowing is done through inheritance.

 

 

Example of Shadowing via Scope:

image

 

 

 

Example of Shadowing via Inheritance:

image

 

 

Example 1:

image

 

In the preceding example, the derived class secondClass shadows display with a Private procedure. When module callDisplay calls display in secondClass, the calling code is outside secondClass and therefore cannot access the private display procedure. Shadowing is defeated, and the compiler resolves the reference to the base class display procedure.

However, the further derived class thirdClass declares display as Public, so the code in callDisplay can access it.

 

 

Example 2:

image

 

 

image

 

 

 

Blogger Labels: Member,tool,properties,developers,regions,purpose,definition,Shadows,modifier,references,Types,region,scope,inheritance,Example,Private,procedure,module,reference,Public,secondClass,callDisplay

No comments:

Post a Comment