codescracker


c#

C# Polymorphism



« Previous Tutorial Next Tutorial »


Polymorphism means having many forms. You can expressed polymorphism as, one interface, multiple functions. Polymorphism in C#, can be:

C# Static Polymorphism

In static polymorphism, the response to a function is simply determined at the program compile time. Here are the two techniques to implement static polymorphism in C# programming:

C# Operator Overloading

Operator overloading in C# are discussed in the chapter C# Operator Overloading.

C# Function Overloading

Sometime, you may have multiple definitions for the same function name in the same scope. The function definition must differ from each other by the types or/and the number of arguments. Here is an example illustrating the concept of function overloading in C#:

/* C# Polymorphism - C# Function Overloading - Example Program */
		
using System;
namespace PolymorphismExample
{
	class PolymorphismClass
	{
		void displayvalue(int i)
		{
			Console.WriteLine("Printing int = {0}", i);
		}	
	
		void displayvalue(double fl)
		{
			Console.WriteLine("Printing float = {0}" , fl);
		}	
	
		void displayvalue(string str)
		{
			Console.WriteLine("Printing string = {0}", str);
		}	
		static void Main(string[] args)
		{
			PolymorphismClass pc = new PolymorphismClass();
			
			// Calling displayvalue to print integer
			pc.displayvalue(5);
			
			// Calling displayvalue to print float
			pc.displayvalue(500.263);
			
			// Calling displayvalue to print string
			pc.displayvalue("Hello C# Polymorphism");
			
			Console.ReadKey();
		}	
	}
}

Now when we compile and run the above program, we will get the following output:

Printing int = 5
Printing float = 500.263
Printing string = Hello C# Polymorphism

C# Dynamic Polymorphism

In dynamic polymorphism, the response to a function is determined at the program run time. Here is an example program, uses dynamic polymorphism in C#:

/* C# Polymorphism - C# Dynamic Polymorphism - Example Program */
		
using System;
namespace PolymorphismExample
{
	abstract class PolymorphismClass
	{
		public abstract int area();
	}	
	class Rectangle : PolymorphismClass
	{
		private int len;
		private int wid;
		public Rectangle(int i=0, int j=0)
		{
			len = i;
			wid = j;
		}
		public override int area()
		{ 
			Console.WriteLine("Rectangle class area = ");
			return (wid * len); 
		}	
	}

	class Tester
	{
		static void Main(string[] args)
		{
			Rectangle ro = new Rectangle(10, 7);
			double ar = ro.area();
			Console.WriteLine("Area = {0}", ar);
			Console.ReadKey();
		}
	}
}

Now when we compile and run the above program, we will get the following output:

Rectangle class area =
Area = 70

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test