Polymorphism in Csharp
Polymorphism in Csharp
In Above Code,
Two methods with the same name but with different
parameters are declared in the class.
The two Square() methods take in parameters of int type
and float type respectively.
Within the Main() method, depending on the type of value
passed, the appropriate method is invoked and the square of
the specified number is displayed in the console window.
Output
Square of integer value 25
Square of float value 6.25
Guidelines and Restrictions
The methods to be overloaded should perform the same
task.
The signatures of the overloaded methods must be unique.
When overloading methods, the return type of the methods
can be the same as it is not a part of the signature.
The ref and out parameters can be included as a part of the
signature in overloaded methods.
Source Code Of Method Overloading In C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace METHOD_OVERLOADING
{
class Program
{
Operator Overloading In C#
This concept resides in Polymorphism.
1. Static polymorphism (compile time polymorphism)
o Method Overloading
o Operator Overloading
Operator Overloading
The concept of overloading a function can also be applied
to operators.
Operator overloading gives the ability to use the same
operator to do various operations.
It provides additional capabilities to C# operators when
they are applied to user-defined data types.
It enables to make user-defined implementations of various
operations where one or both of the operands are of a user-
defined class.
Only the predefined set of C# operators can be overloaded.
Example
Class NewClass
{
public string str;
public int num;
}
Operator Overloading
To make operations on a user-defined data type is not as
simple as the operations on a built-in data type.
To use operators with user-defined data types, they need to
be overloaded according to a programmer’s requirement.
An operator can be overloaded by defining a function to it.
The function of the operator is declared by using the
operator keyword.
Operators may be considered as functions internal to the
compiler.
namespace OperatorOverloading
{
class NewClass
{
public string str;
public int num;
class Program
{
static void Main(string[] args)
{
NewClass obj1 = new NewClass();
obj1.str = "Mohammad";
obj1.num = 20;
Console.WriteLine(obj3.str);
Console.WriteLine(obj3.num);
Console.ReadLine();
}
}
}
namespace METHOD_OVERRIDING
{
class parent
{
public virtual void print()
{
Console.WriteLine("This a method of PARENT class");
}
}
class child : parent
{
public override void print()
{
Console.WriteLine("This a method of CHILD class");
}
}
class Program
{
static void Main(string[] args)
{
parent p = new child();
p.print();
Console.ReadLine();
}
}
}