Search Results

Monday, April 6, 2009

C# Open Discussion

In this topic you can discuss all the problems related to C#.The Experts will try to answer you queries as soon as possible.

Note:
Please mention you name and e-mail address.Our experts will mail you if required.

4 comments:

  1. Shadowing is a concept of polymorphism usage in Object Oriented Programming.

    This is a concept related to over-riding functions at run-time or making a shadow of the object's methods in the inherited classes.

    Let me explain you in terms of technology now. Though it is not much used in programming but it may be used sometimes and its usage is very restrictive and unique.

    ReplyDelete
  2. Implementation of override to override a method
    Suppose you have a base class ClassA in which you have written a method MethodA. Now if you want to inherit this class in a ClassB and use MethodA then the MethodA declared in ClassA will be used but if you override this method in your inherited class classB then it will be over-ridden and the implementation of classB will be used whenever we use it from classB and the implementation of classA will be used whenever we use it from a instance of classA.

    using System;
    using System.Diagnostics;
    using System.IO;
    public class ClassA {
    public virtual void MethodA() {
    Trace.WriteLine( BaseClass MethodA );
    }
    }

    public class ClassB :ClassA{
    public override void MethodA() {
    Trace.WriteLine( SubClass MethodA overridden );
    }
    }

    //implementation class for using the above defined classes
    public class TopLevel {
    static void Main(string[] args) {
    TextWriter tw Console.Out;
    Trace.Listeners.Add(new TextWriterTraceListener(tw));

    ClassA obj new ClassB();
    obj.MethodA(); // Output will be Subclass MethodA overridden
    }
    }

    ReplyDelete
  3. Shadowing instead of overriding
    Upto now the code shown was for overriding a base class method with the child class method But what will happen If you want to provide the base class behaviour instead use the new directive with or without virtual at the base class Is this possible in C#? Yes it is and that is the concept of shadowing in C# using a keyword new' which is a modifier used instead of override .

    public class ClassA {
    public virtual void MethodA() {
    Trace.WriteLine( ClassA Method );
    }
    }

    public class ClassB : ClassA {
    public new void MethodA() {
    Trace.WriteLine( SubClass ClassB Method );
    }
    }

    public class TopLevel {
    static void Main(string[] args) {
    TextWriter tw Console.Out;
    Trace.Listeners.Add(new TextWriterTraceListener(tw));

    ClassA obj new ClassB();
    obj.MethodA(); // Outputs Class A Method

    ClassB obj1 new ClassB();
    obj.MethodA(); // Outputs SubClass ClassB Method
    }
    }

    ReplyDelete