Home Classroom C# .NET C# .NET Part 5

C# .NET Part 5

1375

Welcome to the C#.NET section of the Digit magazine. During the last session we had a closer look at the access modifiers in C#. We saw how they are used and so had a glance at their access capabilities first hand. As we mentioned earlier access modifiers are a very important section in every programming language. They would be used in many different ways in doing programming; hence in long run having an open idea and clear mind on access modifiers could be very advantageous.

In this week we’ll have a look at some object oriented concepts. After all C# is an object oriented programming language, hence all object oriented concepts we know of is applicable and implemented on C#. Here we would talk about encapsulation, polymorphism and inheritance. We would try to implement them through C# as well.

Let’s take a look at each of those concepts in detail.

 

Encapsulation

Encapsulation is an object-oriented principle of hiding the internal state and behavior of an object, making your code more maintainable. In C#, you can manage encapsulation with access modifiers. For example, the public access modifier allows access to any code but the private access modifier restricts access to only members of a type.  Other access modifiers restrict access in the range somewhere between public and private. While you can use any of the access modifiers on type members, the only two access modifiers you can use on types are the public and internal.

using System;

 

namespace Encap

{

    class BankAccount

    {

    public double getBalance()

    {

    return 10000.00;

    }

    }

}

Figure 1: Code on Bank Account Balance

 

In this method ‘getBalance()’ is in a public context. A value is returned from the class. The method is public meaning that it can be called by code that is external to this class.  Now, you can write the following code, elsewhere in your program, to use this method:

BankAccount bank = new BankAccount()

double balance = bank.getBalance();

 

Figure 2: Getting the value in the class

 

In here an object of the ‘BankAccount’ is created. The method would be accessed from that object. Though this is an easy way of getting data, security wise it isn’t very good. Remember that the default access for a type member is private, which we’ll talk about next.  This means that if you forget the public modifier, and didn’t use any modifier at all, you would receive a compiler error.  

The following example would show how to use ‘private’ modifier and use the theory of encapsulation in the code.

 

using System;

 

namespace Encap

{

    class BankAccountPrivate

    {

    private string name;

 

    public string customer_Name

    {

    get { return name;}

    set { name = value;}

    }

    }

}

Figure 3: How to use private modifiers in the code

 

It’s common to encapsulate the state of your type with properties.  In here you can see how the name of the customer is held in the ‘name’ field, but it is wrapped (encapsulated) with the ‘CustomerName’ property. Because ‘name’ is declared as private, code outside the ‘BankAccountPrivate’ class can’t access it directly.  They must use the public customer_Name’ property instead.

 

Now you can change the implementation of ‘name’ in any way you want. This is secure rather than having ‘public’ access to the members. These are two extremes in accessing members. Encapsulation is a concept which is very mush related with access modifiers and behaviors.

 

Inheritance on C#

Classes and Structs are ‘blue-prints’ or templates from which we instantiate (create) objects Example a car may be created based on its blue print Car is the object and blue print is the class (or template).

These are the available types,

An object can be of the following types – Class or Struct There are many differences between the two ‘types’ The main difference between the two is the way in which they are stored in memory and the way they are accessed Classes are also called reference types Structs are known as value types Classes are stored in a memory space called ‘heap’ and Structs are stored in a memory space known as ‘stack’.

Inheritance:

C# supports two types of Inheritance mechanisms

·     Implementation Inheritance

When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance

·     Interface Inheritance

When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

 

Classes support both Implementation and Interface inheritance as they could be inherited from both classes and interfaces. But strcuts only get inherited from interfaces. Structs cannot be derived from another class they are always derived from SystemValueType

P.N: Unlike C++, C# does not support multiple implementation inheritance ‘A’ class cannot be derived from more than one class However; a class can be derived from multiple interfaces.

 

using System;

 

namespace Encap

{

    abstract class Car

    {

    public void startCar()

    {

    }

 

    public abstract bool goForward();

 

    public void stop()

    {

    }

 

    public abstract void turnCar(int whichWay);    

    }

}

Figure 4: Class Car for implement Inheritance

 

In this example class called ‘Car’ is shown, it comprises of few methods. Here you would see some methods have the keyword ‘abstract’. And furthermore the class too is abstract. As name implies abstract methods and classes are not implemented. They should implement overridden in a subclass of the abstract class. Abstract classes and methods are very important. There are some certain facts that should be kept in mind when dealing with abstract classes and methods.

·Abstract class does not necessary have abstract methods.

·In an abstract class few or almost all the methods can be abstract.

·If a method is non abstract, then the class that it belongs must be abstract class.

 

P.N:  A ‘C#’ abstract class contains abstract members which define what a subclass should contain. These abstract members only declare that a member of a particular type is required; it does not implement the member. Implementation of abstract members takes place within the derived class. A subclass which derives from an abstract class and fails to implement abstract methods will fail to compile.

In the above example there are abstract as well as non abstract classes.

Let’s see how this class is sub classed, this is where the concept of inheritance comes into play.

using System;

 

namespace Encap

{

    class SportsCar : Car

    {

    public void startEngine()

    {

    }

 

    public override bool goForward()

    {

    return false;

    }

 

    public override void turnCar(int whichWay)

    {

    }

 

    public void stop()

    {

    }

    }

}

Figure 5: Inheritance in C#.NET

 

Here you could see some of the methods are implemented and some new methods are there as well. “SportsCar : Car” is the way to inherit classes in C#.NET. This would mean that class “SportsCar” is inherited from “Car”. Inheritance is a pretty important and a very useful OOP concept. When inherited a class gets all the qualities from its parent class. Apart from that new qualities and attributes could be included in the new class.

When inheriting a class, you should override methods in its parent class this is very important. In C# we use the keyword ‘override’ to implement inherited methods from a superclass. It is quite evident in the example given, Try to read more on inheritance in C# and gather more knowledge.

 

Polymorphism

 

This is another very important object oriented concept. Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

Here is an example which emphasizes those qualities. This is the parent class that we would use to show the example.

 

using System;

 

namespace Encap

{

    class DrawingObejcts

    {

    public virtual void drawObect()

    {

    Console.WriteLine(“Draw Common Obecjts…..”);

    }

    }

}

Figure 6: Parent class for Drawing Objects

 

The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.

To create a virtual member in C#, use the virtual keyword:

public virtual void drawObect().

Under mentioned are the classes which were derived from the parent class mentioed above, here as in the previous example, a method is over ridden and the content is changed based on the class that it operates on.

P.N : These classes inherit the DrawingObject class. Each class has a drawObect() method and each drawObect() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.

using System;

 

namespace Encap

{

    class DrawCircle : DrawingObejcts

    {

    public override void drawObect()

    {

    Console.WriteLine(“Drawing a Circle…..”);

    }

    }

}

namespace Encap

{

    class DrawingObejcts

    {

    public virtual void drawObect()

    {

    Console.WriteLine(“Draw Common Obecjts…..”);

    }

    }

}

namespace Encap

{

    class DrawSqaure : DrawingObejcts

    {

    public override void drawObect()

    {

    Console.WriteLine(“Drawing a Square….”);

    }

    }

}

Figure7: Example on Polymorphism, the classes that were used.

 

 

Comments

comments

Lakpriya Kottahachchi is an Undergraduate at the Faculty of Information Technology, University of Moratuwa. He enjoys programming with Java and C#.

NO COMMENTS

Leave a Reply