Jun 27

METHOD OVERLOADING BEST PRACTICE – DO’S AND DON’T

METHOD OVERLOADING BEST PRACTICE – DO’S AND DON’T

Let’s briefly understand what is Method Overloading, it is method with same name but with different arguments is called method overloading.

Example of Method Overloading

 


Must follow rules while doing method overloading

1)  Method Body should not be repeated in every method, don’t write same code in every method, instead, call the method by passing default parameter.

 


2) Avoid changing name of parameters for Overloaded Methods

Bad Example:

 

 

In above method you might have notice that we are using different parameter name for Subject and Body, across different method overload function, try to avoid that.

Good Example:

 


3) Avoid changing sequence of parameters for Overloaded Methods, Ordering of overloaded method should be consistent.

Bad Example:

 

In above examples sequence of overloaded method are not consistent. Try to avoid that to avoid confusion and making things complex.

Good Example:

 

Permanent link to this article: http://zappmania.in/2012/06/27/method-overloading-best-practise-dos-and-dont.htm

Jun 27

What is Polymorphisms?

Polymorphism means one interface and many forms. Polymorphism is a characteristics of being able to assign a different meaning or usage to something in different contexts specifically to allow an entity such as a variable, a function or an object to have more than one form.

There are two types of Polymorphism.
Compile time: function or operator overloading
Runtime: Inheritence & virtual functions

 


Example of Compile Time Polymorphism

Method Overloading
– Method with same name but with different arguments is called method overloading.
– Method Overloading forms compile-time polymorphism.
– Example of Method Overloading:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}


Example of Run Time Polymorphism

Method Overriding
– Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
– Method overriding forms Run-time polymorphism.
– Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
– Example of Method Overriding:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

Permanent link to this article: http://zappmania.in/2012/06/27/what-is-polymorphisms.htm