Selection Sort Algorithm

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.
he algorithm works as follows:

  • Find the minimum value in the list
  • Swap it with the value in the first position
  • Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)

Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Here is an example of this sort algorithm sorting five elements:

64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64
(nothing appears changed on this last line because the last)

Selection sort can also be used on list structures that make add and remove efficient, such as a Linked list In this case it's more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far. For example:

64 25 12 22 11

11 64 25 12 22

11 12 64 25 22

11 12 22 64 25

11 12 22 25 64
Source code
using System;
class selectionSort
{
public static void Main()
{
int[] a= new int[100];
int min,pass,i;
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" array elements ");
Console.WriteLine("-----------------------");
for(int j=0;j<x;j++)
{
string s1=Console.ReadLine();
a[j]=Int32.Parse(s1);
}
for(pass=0;pass<x-1;pass++)
{
min=pass;
for(i=pass+1;i<x;i++)
{
if(a[min]>a[i])
min=i;
}
if( min!=pass)
{
int k=a[pass];
a[pass]=a[min];
a[min]=k;
}
}
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Sorted elements of an array are(selection sort)");
for (int j=0;j<x;j++)
Console.WriteLine(a[j]);
}
}

Binary Search Algorithm

binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. The method makes progressively better guesses, and closes in on the location of the sought value by selecting the middle element in the span (which, because the list is in sorted order, is the median value), comparing its value to the target value, and determining if it is greater than, less than, or equal to the target value. A guessed index whose value turns out to be too high becomes the new upper bound of the span, and if its value is too low that index becomes the new lower bound. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference.Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.First, the search item is compared with the middle element of the list. If the search item is less than the middle item of the list, we restrict the search to the upper half of the list; otherwise, we search the lower half of the list.Algorithm.First, the middle element of the sequence is compared to the value we are searching for. If this element matches the value we are searching for, we are done. If, however, the middle element is ``less than'' the value we are chosen for (as specified by the relation used to specify a total order over the set of elements), then we know that, if the value exists in the sequence, it must exist somewhere after the middle element. Therefore we can eliminate the first half of the sequence from our search and simply repeat the search in the exact same manner on the remaining half of the sequence. If, however, the value we are searching for comes before the middle element, then we repeat the search on the first half of the sequence.

Loop for Binary Search

#include 

int binarySearch(int sortedArray[], int first, int last, int key) {
// function:
// Searches sortedArray[first]..sortedArray[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -(index where it could be inserted)-1.
// parameters:
// sortedArray in array of sorted (ascending) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -insertion_position -1 if key is not
// in the array. This value can easily be
// transformed into the position to insert it.

while (first <= last)
{
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
else if (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}

Source code
using System;
class binSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Number of elements in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-----------------------");
Console.WriteLine(" Enter array elements ");
Console.WriteLine("-----------------------");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("--------------------");
Console.WriteLine("Enter Search element");
Console.WriteLine("--------------------");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
int low=0;
int high=x-1;
while(low<=high)
{
int mid=(low+high)/2;
if(x2<a[mid])
high=mid-1;
else if(x2>a[mid])
low=mid+1;
else if(x2==a[mid])
{
Console.WriteLine("-----------------");
Console.WriteLine("Search successful");
Console.WriteLine("-----------------");
Console.WriteLine("Element {0} found at location {1}\n",x2,mid+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

Linear Search Algorithm

linear search is a search algorithm, also known as sequential search,that is suitable for searching a list of data for a particular value.It operates by checking every element of a list one at a time in sequence until a match is found.The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then all previous items mustbe read and checked before the item that matches the search criteria is found.This is a very straightforward loop comparing every element in the array with the key. As soon as an equal value is found, it returns. If theloop finishes without finding a match, the search failed and -1 is returned.For small arrays, linear search is a good solution because it's so straightforward. In an array of a million elements linear search on average willtake500,000 comparisons to find the key. For a much faster search, take a look at binary search.

loop for linear search

int linearSearch(int a[], int first, int last, int key) {
// function:
// Searches a[first]..a[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -1.
// parameters:
// a in array of (possibly unsorted) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -1 if key is not in the array.

for (int i=first; i<=last; i++) {
if (key == a[i]) {
return i;
}
}
return -1; // failed to find key
}
Algorithm

For each item in the database if the item matches the wanted info exit with this item.Continue loop wanted item is not in database

Source code
using System;
class linSearch
{
public static void Main()
{
int[] a= new int[100];
Console.WriteLine("Enter number of elements you want to hold in the array ?");
string s=Console.ReadLine();
int x=Int32.Parse(s);
Console.WriteLine("-------------------------");
Console.WriteLine("\n Enter array elements \n");
for(int i=0;i<x;i++)
{
string s1=Console.ReadLine();
a[i]=Int32.Parse(s1);
}
Console.WriteLine("-------------------------");
Console.WriteLine("Enter Search element\n");
string s3=Console.ReadLine();
int x2=Int32.Parse(s3);
for(int i=0;i<x;i++)
{
if(a[i]==x2)
{
Console.WriteLine("-------------------------");
Console.WriteLine("Search successful");
Console.WriteLine("Element {0} found at location {1}\n",x2,i+1);
return;
}
}
Console.WriteLine("Search unsuccessful");
}
}

GCD Euclidean Algorithm

The greatest common denominator, or GCD, between two numbers is the greatest integer that divides both given numbers. Writing a C# program that can calculate the greatest common denominator (GCD) of large numbers quickily would be very useful.The first idea that comes to mind is perhaps to write a for loop to check all numbers that are less than the pair of numbers to find the GCD. However there is a more efficient way using the Euclidean Algorithm.
Euclidean Algorithm.The Euclidean Algorithm is pretty straight forward: given two numbers, repeatedly replace the larger number with the greater number mod the lesser number. Keep repeating the step until one of the two numbers reaches zero, the other number will then be the greatest common denominator (or greatest common divisor), the GCD.

Recursive

The Euclidean Algorithm lends itself to a recursive C# function (a function that calls itself)
:

public int GCDRecursive(int a, int b)
{
if (a == 0)
return b;
if (b == 0)
return a;

if (a > b)
return GCDRecursive(a % b, b);
else
return GCDRecursive(a, b % a);
}

Non-Recursive

For a variety of reasons, you might want a C# function that is non-recursive. It is not as elegant or simple to understand, but it can be written:

public int GCD(int a, int b)
{
while (a != 0 && b != 0)
{
if (a > b)
a %= b;
else
b %= a;
}

if (a == 0)
return b;
else
return a;
}

Abstract class

Abstract class is a class that has no direct instances, but whose descendants may have direct instances. There are case i which it is useful to define classes for which the programmer never intends to instantiate any objects; because such classes normally are used as bae-classes in inheritance hierarchies, we call such classes abstract classes These classes cannot be used to instantiate objects; because abstract classes are incomplete. Derived classes called concrete classesmust define the missing pieces. Abstract classes normally contain one or more abstract methods or abstract properties, such methods or properties do not provide implementations, but our derived classes must override inherited abstract methods or properties to enable obejcts ot those derived classes to be instantiated, not to override those methods or properties in derived classes is syntax error, unless the derived class also is an abstract class.An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class. Note that an abstract class does not mean that it should contain abstract members. Even we can have an abstract class only with non abstract members

using System;
namespace abstractSample
{
//Creating an Abstract Class

abstract class absClass
{
//A Non abstract method

public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}

//An abstract method, to be

//overridden in derived class

public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//A Child Class of absClass

class absDerived:absClass
{
[STAThread]
static void Main(string[] args)
{
//You can create an

//instance of the derived class

absDerived calculate = new absDerived();
int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine("Added : {0},
Multiplied : {1}", added, multiplied);
}

//using override keyword,

//implementing the abstract method

//MultiplyTwoNumbers

public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}
}

In the above sample, you can see that the abstract class absClass contains two methods AddTwoNumbers and MultiplyTwoNumbers. AddTwoNumbers is a non-abstract method which contains implementation and MultiplyTwoNumbers is an abstract method that does not contain implementation.

The class absDerived is derived from absClass and the MultiplyTwoNumbers is implemented on absDerived. Within the Main, an instance (calculate) of the absDerived is created, and calls AddTwoNumbers and MultiplyTwoNumbers. You can derive an abstract class from another abstract class. In that case, in the child class it is optional to make the implementation of the abstract methods of the parent class.

Abstract properties

Following is an example of implementing abstract properties in a class.

//Abstract Class with abstract properties
abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}

class absDerived:absClass
{
//Implementing abstract properties

public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}

Important rules applied to abstract classes

  • An abstract class cannot be a sealed class
  • An abstract method cannot be private.
  • The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
  • An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
  • An abstract member cannot be static
  • Virtual method has an implementation & provide the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method
  • A class can inherit one or more interfaces, but only one abstract class
Abstract class vs. Interface
  • An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class
  • The members of the interface are public with no implementation. Abstract classes can have protected parts, static methods, etc.
  • A class can inherit one or more interfaces, but only one abstract class.
  • No fields can be defined in interfaces.An abstract class can have fields and constrants defined
  • Abstract classes can add more functionality without destroying the child classes that were using the old version. In an interface, creation of additional functions will have an effect on its child classes, due to the necessary implementation of interface methods to classes.

Inheritance

Inheritance is one of the most important, and most powerful, of the object-oriented programming concepts. Using inheritance, one class can be derived from another. The derived class, also known as the child class or subclass, inherits functionality from the base class, also known as the parent class or superclass. The subclass can add methods and properties or modify the functionality that it has inherited to provide a more specialised version of the base class.The concept of inheritance brings something of a real-world view to programming. It allows a class to be defined which has a number of characteristics and then other classes to be created which are derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own. C# is known as a single inheritance programming language. Using inheritance, classes become grouped together in a hierarchical tree structure. The more generalised classes appear at the root of the hierarchy with the more specific classes appearing on the tree's branches. This categorisation of classes into related types is why inheritance is sometimes referred to as generalisation

An Example of Inheritance

public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;

public int getAccountNumber()
{
return accountNumber;
}

public void setAccountNumber(int newNumber)
{
accountNumber = newNumber;
}
}
public class SavingsAccount : BankAccount
{
}

Here we created a class called BankAccount.This class does a good job of defining characteristics common to any type of bank account, such as account holder name, account number and current balance. Imagine, however, that our banking program needs to support a number of specific types of account. For example, the bank might offer its customers an interest bearing savings account. A savings account will have all the characteristics of our BankAccount class but would also need a way to store the prevailing interest rate. One option would be to create a brand new class from the ground up called SavingsAccount which duplicates everything we have in our BankAccount class, plus extra members needed for a savings account. Another, more efficient method is to derive a SavingsAccount class from the BankAccount class and then add in the extra functionality into this subclass.

Creating a Subclass in C#

Subclasses are declared in the same way as any other class with the exception that the class name is followed by a colon (:) followed by the name of the class from which it is to inherit. With this in mind we can begin by creating our SavingsAccount class:

public class SavingsAccount : BankAccount
{
public double interestRate;

public SavingsAccount (string name, int number, int balance, double rate)
: base (name, number)
{
accountBalance = balance;
interestRate = rate;
}

public double monthlyInterest()
{
return interestRate * accountBalance;
}
}
We now have a new class called SavingsAccount which inherits all the members of the BankAccount class and adds some members of its own. In particular we have added a new data member called interestRate which will store the interest rate paid on the account together with a new method to calculate the monthly interest.

Passing Arguments to the Base Class Constructor

In the BankAccount base class we have a constructor which takes the account name and account number as arguments. In the SavingsAccount subclass we need to accept two additional arguments - the balance and the interest rate. The : base code instructs C# to handle the name and number arguments using the constructor from the base class. The remaining two arguments are then passed to the SavingsAccount constructor.
With our subclass complete we can now make use of it:
static void Main()
{
SavingsAccount saveAccount = new SavingsAccount("Fred Wilson", 123456, 432, 0.02F);

Console.WriteLine ("Interest this Month = " + saveAccount.monthlyInterest() );
}

Interfaces


An Interface is a named collection of semantically similar abstract members or functions. A class or a structure may follow a behaviour that is prescribed by an interface. The keyword interface is used to create an interface. Note that while defining members inside an interface, there is no need to specify the access specifier, as they are public by default. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. You can implement any number of interfaces in a single derived class, but you should provide signatures to all method definitions of the corresponding interfaces.


Why Use Interfaces?

  1. To allow a class to inherit multiple behaviors from multiple interfaces.
  2. To avoid name ambiguity between the methods of the different classes as was in the use of multiple inheritance in C++.
  3. To combine two or more interfaces such that a class need only implement the combined result.
  4. To allow Name hiding. Name hiding is the ability to hide an inherited member name from any code outside the derived class.

How to implement an interface in C#?

An interface may be implemented using the keyword "implements" in VB.NET
and using a colon in C#. See code C# example below:

interface IBooks
{
long int Cost { get; } //Interface property
}

//ComputerBooks is a class that implements an Interface IBooks

public class ComputerBooks : IBooks

{

// Implementation of the property

public long int Cost
{
get { return 100; } //Read only value
}

}
How to declare and implement an interface?
Interfaces can be declared with the keyword interface and can be implemented in a class
using System;
interface Interdemo
{
void Show();
}

class Interimp:Interdemo
{
public void Show()
{
Console.WriteLine("Show() method Implemented");
}

public static void Main(string[] args)
{
Interimp inter = new Interimp();
inter.Show();
}
}
Combining Interfaces
Two or more interfaces can be combined into a single interface and implemented in a class

using System;
interface Interdemo
{
void Show();
}

interface Interdemo1
{
void Display();
}

interface Combineinter:Interdemo,Interdemo1
{
//Above interfaces combined
}

class Multipleinterimp:Combineinter
{
public void Show()
{
Console.WriteLine("Show() method Implemented");
}

public void Display()
{
Console.WriteLine("Display() method Implemented");
}

public static void Main(string[] args)
{
Multipleinterimp inter = new Multipleinterimp();
inter.Show();
inter.Display();
}
}
Using Methods, Indexers, Properties, and Event Within an Interface
interface IIntelligence
{
/// Method declaration within the interface
bool intelligent_behavior();

/// Indexer declaration within the interface
object this[int index]
{
get;
set;
}
/// Event declaration within an interface
/// testEvent should also be declared as a delegate before
event testEvent IQEvent;

/// Property declaration within an interface
string IQProperty
{
get{}
set{}
}
}
Using "Is" and "As" Operators to Verify the Implementation of an Interface

Think what will happen if an object attempted to use a class as though the class had implemented a method that is not defined in it; you will get an exception at runtime. To remove this ambiguity, we use the "is" keyword to verify that the method exists in the class implementing the given interface.

I will use the same code of the Mammal class above for explaining this. Here, we need to change only the Main ( ) because we only need to check that our created object is either implementing the interface or not.

if(human is IIntelligence)
{
IIntelligence humanIQ = (IIntelligence)human;
humanIQ.intelligent_behavior();
}
In the example case above, when you will run it, it will give a warning that "the given expression is always of the provided type" and the validity is also been checked twice: one in using the "is" operator and the other when casting it to the interface type.

Therefore, we can use the "as" operator to cast and check the types more efficiently. The "as" operator returns an object type and null if the type mismatched whereas the "is" operator returns a Boolean value. Here, no warning will be generated.

IIntelligence humanIQ = human as IIntelligence;

if(null != humanIQ)

{
humanIQ.intelligent_behavior();
}
Multiple Inheritance using C# interfaces
This can be done using child class that inherits from any number of c# interfaces. The inheritance can also happen with a combination of a C# .Net class and c# interfaces. Now let us see a small piece of code that demonstrate us multiple inheritance using only interfaces as parent data types.

    class ClonableNode : INode,ICloneable
{
public object Clone()
{
return null;
}
// INode members
}
The above example created a class ClonableNode. It implements all the functionality of INode interface in the same way as it was done in Node class. Also it realizes Clone method only one item of IClonable interface of .NET library.

Polymorphism

  • When a message can be processed in different ways is called polymorphism."Poly" means many
  • When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class
  • C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to
  • It allows you to invoke methods of derived class through base class reference during runtime
  • It has the ability for classes to provide different implementations of methods that are called through the same name

Polymorphism is of two types:

  • Compile time polymorphism/Overloading
  • Runtime polymorphism/Overriding

Compile Time Polymorphism

  • Compile time polymorphism is method and operators overloading. It is also called early binding
  • In method overloading method performs the different task at the different input parameters
  • Use method overloading in situation where you want a class to be able to do something, but here is more than one possibility for what information is supplied to the method that carries out the task
  • You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing
Example
 using System;
namespace method_overloading

{
class Program
{
public class Print
{
public void display(string name)

{
Console.WriteLine("Your name is : " + name);
}

public void display(int age, float marks)

{
Console.WriteLine("Your age is : " + age);

Console.WriteLine("Your marks are :" + marks);
}
}

static void Main(string[] args)

{
Print obj = new Print();

obj.display("George");

obj.display(34, 76.50f);

Console.ReadLine();
}
}
}
Main points to be remembered while overloading are

  • If you use overload for method, there are couple of restrictions that the compiler imposes
  • The rule is that overloads must be different in their signature, which means the name and the number and type of parameters
  • There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name

Here is an example to overload multiple methods

using System;
namespace method_overloading_polymorphism
{
class Program
{
public class Shape

{
public void Area(float r)
{
float a = (float)3.14 * r;

// here we have used funtion overload with 1 parameter.

Console.WriteLine("Area of a circle: {0}",a);
}

public void Area(float l, float b)

{
float x = (float)l* b;

// here we have used funtion overload with 2 parameters.

Console.WriteLine("Area of a rectangle: {0}",x);

}
public void Area(float a, float b, float c)

{
float s = (float)(a*b*c)/2;

// here we have used funtion overload with 3 parameters.

Console.WriteLine("Area of a circle: {0}", s);
}
}
static void Main(string[] args)
{
Shape ob = new Shape();

ob.Area(2.0f);

ob.Area(20.0f,30.0f);

ob.Area(2.0f,3.0f,4.0f);

Console.ReadLine();
}
}
}
Runtime Time Polymorphism

  • Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism
  • It is also called late binding.

Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.

Inherited Methods

A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A {}

class Test
{
static void Main(string[] args)
{
A a = new A();
a.Foo(); // output --> "A::Foo()"

B b = new B();
b.Foo(); // output --> "A::Foo()"
}
}
}
The method Foo() can be overridden in classes B and C:


using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
public void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
static void Main(string[] args)
{
A a;
B b;
a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"
a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}
There are two problems with this code.
  • The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section
  • Although the code compiles and runs, the compiler produces a warning: ...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'

This issue will be discussed in section Hiding and Overriding Methods.

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System;
namespace Polymorphism
{
class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A
{
public void Foo() {}
}

class B : A
{
public virtual new void Foo() {}
}


A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}

Template by - Mathew | Mux99