Wednesday, January 1, 2014

Overloading, Overriding and hiding in C#

Overloading and overriding are concepts in polymorphism.

Overloading

Use overloading when multiple methods has same purpose but there is more than one way to do. Overloaded methods have different parameters.

E.g:
void ReadXml(string fileName) {  }
void ReadXml(Stream strm) {  }

An alternative to method overloading is to use optional parameters.
public void Foo(int x = 1)

Also use named parameters for readability.
t.Foo(x: 12);

You can also use params keyword to have unlimited no. of arguments of a specified type like below,\

        public int Foo(params int[] x)
        {
            return x.Sum();
        }

call it like,
t.Foo(1, 2, 3);

Overriding

Concept in which subclasses provides specific implementation of a method provided by the super class.

    class A
    {
        public virtual string Method()
        {
            return "A";
        }
    }

    class B : A
    {
        public override string Method()
        {
            return "B";
        }
    }

    class C : A
    {
        public string Method()
        {
            return "C";
        }
    }

            A a = new A();
            Console.WriteLine(a.Method()); //A

            A a2 = new B();
            Console.WriteLine(a2.Method()); //B

            B b = new B();
            Console.WriteLine(b.Method()); //B

            C c = new C();
            Console.WriteLine(c.Method()); //C

In the last example, c.Method() hides a.Method(). Therefore it gives a warning. To remove the warning append new in front of  public string Method()

http://stackoverflow.com/questions/3838553/overriding-vs-method-hiding

http://stackoverflow.com/questions/25008021/why-does-this-c-sharp-code-return-what-it-does/25008171#25008171

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook