Polymorphism, Method Hiding and Overriding in C#

Overview

One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning “having multiple forms”) in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow a variable to refer to more than one type of object.

Inherited Methods

A method Sadi() 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 Sadi() { Console.WriteLine("A::Sadi()"); }
        }

        class B : A {}

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

                B b = new B();
                b.Sadi();  // output --> "A::Sadi()"
            }
        }
    }
      

The method Sadi() can be overridden in classes B and C:

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

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

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

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

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

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

Methods (Use of override keyword)Virtual and Overridden

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 Sadi() { Console.WriteLine("A::Sadi()"); }
        }

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

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

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

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

Method Hiding (Use of new keyword)

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 Sadi() { Console.WriteLine("A::Sadi()"); }
        }

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

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

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

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

C# Access Modifier

C# Access Modifier

Meaning in Life

public

Marks amember as accessible from an object variable as well as any derived classes.

private

Marks a method as accessible only by the class that has defined the

method. In C#, all members are private by default.

protected

Marks a method as usable by the defining class, as well as any derived

classes. Protected methods, however, are not accessible from an object

variable.

internal

Defines a method that is accessible by any type in the same assembly,

but not outside the assembly.

protected internal

Defines a method whose access is limited to the current assembly or

types derived from the defining class in the current assembly.

Class Modifiers and their uses in C# .Net

Class/Interface (Base class)

Inheritance (Inherited class)

Implementation (Interface)

(Child)

(Instance)

Is initiated??

General

Abstract

Sealed

Static*

General

Yes

Yes

Yes

No

No

Yes

Abstract

Yes

Yes

Yes

No

No

No

Sealed

No

No

No

No

No

Yes

Static

No

No

No

No

No

No

Interface

Yes

Yes

Yes

No

Yes

No

 

 

 


 

 

 

 

 

This table is for showing relationship between a base class and child class

In this table I want to show the accessibility among the various types of classes and interface. From this table you also can know what type of class can be initiated. This is one example that helps you to understand the table.

If you use Abstract class as base class and take a general class as child and want to inherit, this will possible …here you can see..

Base: Abstract (ASadi)

Child: Interface (Sadi)

Accessibility: Yes

abstract class Sadi : ASadi

{

#region ASadi Members

public int getint() {

throw new Exception(“The method or operation is not implemented.”); }

#endregion

}

If you execute this code, it executes properly

From the first column of the table we can say that general class inherites both general and abstract class and also implements an interface. These classes cannot inherites sealed as well as static class. Only General and Sealed classes can be initiated.

From the table and above discussion we can conclude that,

Abstract Class

A class defined as abstract is used as a base class. Such a class is used for the purpose of inheritance only i.e. other classes are derived from this class. We cannot create an object of an abstract class. An abstract class may contain methods and properties. The classes derived from the abstract class inherit these methods and properties. The abstract class may also contain abstract methods and properties. Abstract method and properties do not have any functionality. The derived class defines their full functionality.

Here is an example of an abstract class:

abstract class MyAbstract { public abstract void AbMethod(); }

Sealed Class

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

public sealed class classSealed { // Class members here. public string ID; public double Price; }

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one cannot derive from it. Sealing a method means one cannot override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing). In C# a method cannot be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

Static Class

Static classes are classes that contain only static members. Following is an example of static class. public static MyClass { …..}

A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Following are the main features of a static class:

·         They only contain static members.

·         They cannot be instantiated.

·         They are sealed.

·         They cannot contain Instance Constructors (C# Programming Guide).

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).

 

Difference between Namespace and Assembly in C# .Net

Assembly will contain Namespaces, Classes, Data types it’s a small unit of code for deployment. Assembly defines the name of the .dll file.
Namespace is used in order to avoid conflict of user defined classes

Namespace:
1) it is a Collection of names wherein each name is Unique.
2) They form the logical boundary for a Group of classes.
3) Namespace must be specified in Project-Properties.

Assembly:
1) It is an Output Unit.
2) It is a unit of Deployment & a unit of versioning.
3) Assemblies contain MSIL code.
4) Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).
7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

Simple Example of Inheritance and Interface (why do we use Inheritance and interface) in c# .Net

using System;
using System.Collections.Generic;
using System.Text;
interface Talkable
{
string Table();
}
class Animal { }
class Cat : Animal, Talkable
{
string Talkable.Table() { 
return "miao"; 
}
}
class Dog : Animal, Talkable
{
string Talkable.Table(){
return "bulk"; 
}
}
class Elephant : Animal
{
}
class MainClass
{
static void Main()
{
Animal[] AnimalArray = new Animal[3];
AnimalArray[0] = new Cat();
AnimalArray[1] = new Elephant();
AnimalArray[2] = new Dog();
foreach (Animal a in AnimalArray)
{
Talkable b = a as Talkable;
if (b != null)
Console.WriteLine("Baby
is called: {0}", b.Table());
}
}
}
output:
Baby is called: miao
Baby is called: bulk

Difference between class and struct in C# .Net

1. Classes are reference types and structs are value types.
Since classes are reference type, a class variable can be assigned null.But we cannot assign null to
a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs.But classes can have
example:
class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors. But structs cannot have
7. Classes must be instantiated using the new operator. But structs can be
8. Classes support inheritance.But there is no inheritance for structs.
( structs don’t support inheritance polymorphism )
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.11. A class is permitted to declare a destructor.But a struct is not
12. classes are used for complex and large set data. structs are simple to use.

Dynamic Method Invocation in C# .Net (Static Method and Non Static Method)

Create a solution in visual studio and add two project. First project name is  “FirstProject” and second one is “DynamicInvoke”. In the first project add Class1.cs class and compile.

Class1.cs

using System;
public class Class1{
public static String method1()
{
return "I am Static method (method1) in class1";
}
public String method2()
{
return "I am a Instance Method (method2) in Class1";
}
public String method3(String s)
{
return "Hello " + s;
}
}

DynaInvoke.cs

using System;
using System.Reflection;
class DynamicInvoke
{
public static void Main(String[] args)
{
Assembly MyAssembly = Assembly.Load("FirstProject");
//For getting the assembly click the right mouse on the class1 oject then go to the property
Type MyType = MyAssembly.GetType("FirstProject.Class1");
//class name should be added with assembly like (assemblyName.className) (NameSpace with classname)
object MyObj = Activator.CreateInstance(MyType);

//Invoking a static method (How to invoke a static method??)
String str = (String)MyType.InvokeMember("method1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });
Console.WriteLine(str);

//Invoking a non-static method (How to invoke a non static method??)
str = (String)MyType.InvokeMember("method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, new object[] { });
Console.WriteLine(str);

//Invoking a non-static method with parameters (How to invoke a non static method with parametres??)
object[] MyParameter = new object[] { "Sadi" };
str = (String)MyType.InvokeMember("method3", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, MyParameter);
Console.WriteLine(str);
}
}

In the second project add this code and run..