Lesson 4:Classes, Inheritance, Interfaces, Structures and Enums




   Classes,
 Inheritance, 
   Interfaces, 
  Structures 
  and Enums

Image by Cool Text: Free Graphics Generator

Classes, Inheritance, Interfaces, Structures and Enums

Classes

A class can be defined as the container of objects,methods,variables,fields,properties etc.They will be discussed later in detail .

The class members denote class behavior as well as the data within the class.Data may be defined as the logically valid collection of information.Information is defined as the raw data.
The constructors and destructors are not the members of the class (mind you)

As C# is a strong object oriented programming supportive language;every class is derived from the object class.

In order to work with the members of the class (except static and abstract classes), we have to create an instance of the object of that class by using the new keyword.

Unlike other member(s) of a class, we can not declare the object(s) of that class.Declaring is done to inform the compiler about the members,their types,modifiers etc. before execution.Where as object is created at run-time.So how can we declare something which has not yet been created?

Examples

Example 1

using System;

namespace ClassExample1

{

// This is the way to declare a class by using the keyword class.

class MyCircle
{

/* radius of the circle.The concept of global variable is replaced by the term public field.The public modifier is used to make the field rad visible outside the class */

public double rad;
}

class MainClass

{

static void Main(string[] args)

{

/* declaring Circl of type MyCircle .It is the way to call the instance of the classe which contains members of the class */

MyCircle Circl = new MyCircle();

/* accessing a public field of the class named rad and assigning it the value of 2 by dotted notation or scope resolution operator. The scope resolution is the way to access the class member (s) */

Circl.rad = 2;

//declaring a variable rd and initializing it to the value contained in rad

double rd=Circl.rad;

double Area = 3.142 * rd * rd;

Console.WriteLine(“Area of the Circle is {0}”, Area);

}

}

}

Output

Area of the Circle is 12.568

Note: Members are the attributes of the object of the class.They should be kept private for the encapsulation.Encapsulation is a way to make the data secure from outside access to the class members to prevent the data in-consistency

Accessing private members through public methods of the class

This is the smart way to access the private members of the class by its public methods.By doing this, we are preventing the unneeded changes in the actual values of the members outside that class.

Example 2

using System;

namespace ClassExample2

{

class MyCircle {

/* Initializing the field to value 2 and make it private so that it is not visible outside the class */

private double rad=2;

/The * Public member function of the class MyCircle. This method has its definition or prototype (Execution block of code) inside the class MyCircle with return type double*/

public double CalculateArea()
{

return 3.142 * rad * rad;

}

}

class MainClass

{

static void Main(string[] args)

{

// instantiating the class

MyCircle Circl = new MyCircle();

// calling the method CalculateArea and returning its value to Area variable
double Area = Circl.CalculateArea();

Console.WriteLine(“Area of the Circle is {0}”, Area);

}

}

}

Output

Area of the Circle is 12.568

Note: Example 2 is the better approach than Example 1

Properties

Properties are the named members of class,structure or interface.They are used to access the private members as well as protected members.

In comparison to methods, fields do not perform complex computations. They are used to just get or set the values of the members with some normal operations. Use them in place of methods whenever there is a simple operation to be performed.

Examples

Example 1

using System;

class Wrestler

{

private string place = “Unknown”;

private float height = 0;

private string name= “Unknown”;

private int weight = 0;

// Declaring ‘Height’ property

public float Height

{

get

{

// TAKE THE VALUE OF HEIGHT VARIABLE

return height; }

set

{

// ASSIGN THE VALUE TO THE HEIGHT VARIABLE
height = value;

}

}

public string Place

{

get

{

return place;

}

set

{

place = value;

}

}

public string Name

{

get

{

return name;

}

set

{

name= value;

}

}

public int Weight

{

get

{

return weight;

}

set

{

weight = value;

}

}

public static void Main()

{

// INSTANTIATE THE WRESTLER OBJECT.
Wrestler w = new Wrestler();

//SET THE PROPERTIES WITH THE VALUES
w.Height = 7;

w.Name = “Undertaker”;

w.Weight =300;

w.Place = “Death Valley”;

Console.WriteLine(“From : {0} , Weighing: {1} lbs, Height : {2} feet… The {3}”,w.Place,w.Weight,w.Height,w.Name);

Console.ReadKey(); // ReadKey() helps console screen remain visible when debugging till the key is pressed

}

}

Output

From : Death Valley , Weighing: 300 lbs, Height: 7 feet… The Undertaker

Note:Explore yourself examples like:

1.get; set;

Example

using System;

class myClass
{
public double myValue
{
get;
set;
}
}

class Program
{
static void Main()
{
myClass obj=new myClass();
obj.myValue =2;
obj.myValue/=2;//also written as obj.myValue=obj.myValue/2;
Console.WriteLine(“The result is:{0}”,obj.myValue);
}
}

 

Output

The result is: 1

 

2. using private set property (Look at the first code and its description)

3. public string Name (Click here and see the first program only)

{ get

{
return name;
}
protected set
{
name = value;
}
}

4.Read-Only get property (Click here and read about read-only property)
 

Constructor

A constructor is a an instantiating method of a class which is executed each time when the object is created from the class.The name of the constructor of the class is the same as that of the class.A class can have multiple constructors.

Example:

using System;

class Wrestler

{

private string place = “Unknown”;

private float height = 0;

private string name= “Unknown”;

private int weight = 0;

// Declaring ‘Height’ property

public float Height

{

get

{

return height;

}

set

{

height = value;

}

}

public Wrestler()

{

name = “Undertaker”;

height = 7;

weight = 300;

place = “Death Valley”;

}

public string Place

{

get

{

return place;

}

set

{

place = value;

}

}

public string Name

{

get

{

return name;

}

set

{

name= value;

}

}

public int Weight

{

get

{

return weight;

}

set

{

weight = value;

}

}

public static void Main()

{

Wrestler w = new Wrestler();

Console.WriteLine(“From : {0} , Weighing {1} lbs, Height {2} feet… The {3}”,w.Place,w.Weight,w.Height,w.Name);

Console.ReadKey(); // ReadKey() helps console screen remain visible when debugging till the key is pressed

}

}

Output

From : Death Valley , Weighing: 300 lbs, Height: 7 feet… The Undertaker

In the above example, we have initialized the private variables of Wrestler class with the Wrestler () constructor.

Now we have to see what happens if we just eliminate all the initializations of the variables and leave the constructor’s body blank.The output will show the very initial values of the variables

Output

From : Unknown , Weighing: 0 lbs, Height:0 feet…The Unknown

Constructor Return Type

The constructor does not return a value specified by the user just like other methods. However we can do the trick of throwing exceptions (will be discussed later) inside the constructor

I sometimes, like to add the references.So here it is

public class MyType
{
public MyType(int toValidate)
{
if (toValidate < 0)
{
throw new ArgumentException(“toValidate should be positive!”);
}
}
}

We are throwing an exception that if the value inside the parameter of a constructor is lesser than zero then the exception is to be thrown.

The above example clearly mention the use of parameters inside the constructor. So yes; constructors support parameters.

http://stackoverflow.com/questions/13497626/how-to-return-a-value-using-constructor-in-c

There are some excellent examples in msdn site

http://msdn.microsoft.com/en-us/library/ms173115%28v=vs.90%29.aspx

One thing I want to mention is the concept of polymorphism.When a method having same name is used in different ways such that it’s parameters differ or has different signature(s).It is said to be polymorphic.

The example in the above mentioned link is applying the concept of polymorphism

Example

public class Employee
{
public int salary;

public Employee(int annualSalary)
{
salary = annualSalary;
}

public Employee(int weeklySalary, int numberOfWeeks)
{
salary = weeklySalary * numberOfWeeks;
}
}

Destructors

Destructor is an opposite of constructor.It destroys the instance of the class.It can’t be used in structure.Only one destructor exists for a class.Destructors cannot be inherited or overloaded.The destructor cannot be invoked by the coder. They are invoked automatically.A destructor does not have access modifier(s) or parameter(s).

Note:

* Constructors also support ref and out parameters.Do some experimentation with them.

* We use new keyword to instantiate class object

* Classes are reference types that’s why they are on heaps.

* The this keyword refers to the current instance of the class

Examples

Example 1

public Restaurant(string manager, int age)
{
this.manager = manager; //Qualifying manager variable with current manager
this.age = age;
}

Example 2

AddThis(this); // to pass an object as a parameter of the current instance

Structures:

Basically every type such as int,char,float is a structure.We use user defined structure with the word struct in order to keep different data type members together .It looks just like as class but it is a value type, that’s why it resides on stack.Structure provides not as much flexibility as a class.They are used for lesser complex scenarios.

If the objects are smaller; then structure might be the option .For larger objects and to support inheritance,
always use classes.
Structures may contain constructors, constants, fields, methods, properties, indexers, operators, events etc.

For more differences between classes and structures;refer

http://msdn.microsoft.com/en-us/library/aa664471%28v=vs.71%29.aspx

this keyword

Examples

The this keyword is used to denote the current instance of an object.

Example 1
// Without an access modifier,an object is always public
class myClass
{
private string _manager;
private int _age;

/*
The this keyword is assigning the
values inside the parameters of the method Company()
to the private fields of the current instance of myClass object

*/

public void Company(string manager, int age)
{
//Qualifying ‘manager’ variable with current manager
this._manager = manager;
this._age = age;
}
}

Example 2

// to pass an object as a parameter of the current instance
AddThis(this);

Example 3

using System;

class Program
{
struct MyStruct
{
public int number;
public bool truefalse;
public float floating;
};

static void Main()
{
MyStruct s; // this is how we refer structure variables
s.number = 1; // the dot is the scpoe resolution operator
s.truefalse = true;
s.floating = 2;
Console.WriteLine(“Number={0},TrueFalse={1},Floating={2}”,s.number,s.truefalse,s.floating);

}
}

Output

Number=1,TrueFalse=true,floating=2

Refer Constant keyword and its importance

Constructor

The constructor in a structure always consists of parameters .
Structure members automatically have their default values

msdn has an excellent example for structures.Refer the link below and check the first program

http://msdn.microsoft.com/en-us/library/aa288208%28v=vs.71%29.aspx

Inheritance

Inheritance is the backbone of object oriented programming.As C# fully supports OPP concept, inheritance is the asset in this style of coding.

The basic theme of inheritance begins with the term relationship or derivation between the classes,structures,interfaces etc.

A class from which another class derives is known as Base Class, whereas the derived classes are called Derived Class.

Points to be noted are :

*A derived class has only one base class

* The derived class can thereby reuse the code in the base class without having to re-implement it. In the derived class, you can add more members. In this manner, the derived class extends the functionality of the base class.

Ref http://msdn.microsoft.com/en-us/library/ms173149.aspx

Examples

using System;
using System.Text;

namespace Inheritance1
{
// this is the base class or parent class
public class Bank
{

// camel-case representation for fields for more professional approach

private int bankID = 0;
private string employeeName = “Unknown”;
private string employeeType = “Unknown”;

protected int BankID
{

get
{

return this.bankID;

}

set
{

this.bankID = value;

}

}

protected string EmployeeName
{

get
{

return this.employeeName;

}

set
{

this.employeeName = value;

}

}

protected string EmployeeType
{

get
{

return this.employeeType;

}

set
{

this.employeeType = value;

}

}

/* We are using two new words here.One is ‘protected’ and the other is ‘static’

The word ‘protected’ is an access modifier which is used to indicate that any class member,
when represented by ‘protected’ keyword,is visible to its derived class and no other

//The top level class can never be protected in nesting the classes.We will see nested classes later
public class outerClass
{
protected class innerClass
{
}
}
class can view it.The ‘static’ word denotes that the method is not an instance method of the
class.It can be invoked directly by using class name.For example
class MyClass
{
public int someInstance() { return 1; }
public static int nonInstance()
{ return 2;
}
}

* static void main()
*
* {
*
* MyClass instance = new MyClass();
instance.someInstance(); //Ok
instance.nonInstance(); //Compilation error
MyClass.someInstance(); //Compilation error
SomeClass.StaticMethod(); //Ok
}

*/
//this is the static method
protected static void SetNewValues()
{

Bank bnk = new Bank();
bnk.bankID = 1546;
bnk.employeeName = “Ahmed”;
bnk.employeeType = “Manager”;

Console.WriteLine(“Bank-ID={0} n Employee Name={1} n Employee {2}”, bnk.bankID, bnk.employeeName, bnk.employeeType);

}

}

/* ‘:’ qualifier is used to indicate that the left side class ‘Department’
* is the derived class of ‘Bank’ class.

*/

public class Department : Bank
{

/* Extending the base class members further
* in the derived class
*/
private int departmentID = 1678;
private string departmentName = “I.T”;

protected int DepartmentID
{

get
{

return this.departmentID;

}

set
{

this.departmentID = value;

}

}

protected string DepartmentName
{

get
{

return this.departmentName;

}

set
{

this.departmentName = value;

}

}

/* This method is intentionally kept public otherwise
* it won’t be visible to main() method

*/
public void AddMoreMembers()
{
// direct invocation of static method
Bank.SetNewValues();
Console.WriteLine(“DepartmentID={0} n DepartmentName={1}”, DepartmentID, DepartmentName);

}

}

class Program
{
static void Main(string[] args)
{

//invocation through an instance
Department dept = new Department();
dept.AddMoreMembers();

}
}
}

Output

Types of classes

Abstract Class

The abstract class is just a template or prototype class which consists of abstract members.The abstract class provides the prototype for the derived classes

Examples

Example 1

using System;
class Science
{

public abstract class Physics

{

/* abstract method PhysicsClass() is never implemented in abstract class.No abstract methods are implemented in the abstract without any hassle*/

public abstract void PhysicsClass() ;

}

//Quantumphysics class derived from abstract Physics class

public class Quantumphysics : Physics

{

/*method belonging to Physics class is implemented or overridden in the derived class.

Here,the complete function definition is present */

public override void PhysicsClass()
{
Console.WriteLine(“Physics class”);
}
}

static void Main()

{

//Creating an instance of Physics class object

Physics obj=new Physics();

 

//calling the method through the instance of the class

obj.PhysicsClass();
}
}

Output

Physics class

Note: We always use override keyword when we are implementing the abstract method of the base class.If we want to implement the member of the abstract class in that class,then we must remember to use the keyword override

Nested Classes

For all encapsulation lovers,there is also a concept of nested classes or classes within the classes.This extends the concept of encapsulation further

Example

using System;

 

public class MainClass

{

 

private int number = 1;

 

private class NestedClass

{

 

private static int number = 2;

 

static void Main()

{

 

/* How we are accessing the private field of the

main class in the nested class*/

 

MainClass objMain = new MainClass();

int sum = number + objMain.number;

Console.WriteLine(“Sum of the numbers of two classes:{0}”, sum);

Console.ReadKey();

}

 

Sealed Class

The purpose of abstraction lies in the fact that we can use abstract methods with the same names and perform different functions by changing their signatures or parameters.This is termed as

method overloading

A class,struct or an interface can overload a method with different signatures or parameters,having the same name.A good example is the ToString() method.We expect that the readers will read the overloads in this method.

Example

using System;
public class MyClass
{
public virtual void MyMethod()
{
Console.WriteLine(“Overloading the method with virtual keyword”);
}
}
public class MyDerivedClass : MyClass
{
public override void MyMethod()
{

Console.WriteLine(“Overriding the method with override keyword”);

}
}

class Program
{
static void Main(string[] args)
{

MyClass BaseClass = new MyClass();
BaseClass.MyMethod();

MyDerivedClass DerivedClass = new MyDerivedClass();
DerivedClass.MyMethod();

}
}

Note: The parameter output in the derived class has been changed.Always use the word “override” to override a method

Sealed Class

A Sealed Class can not be used as a base class.This is useful for better program optimization.

Example

public sealed class MyClass
{// Members}

Derived class members overriding the virtual methods of the base class can also use the term sealed for preventing the over-riding. This thing doesn’t allow further derivation of the method.The new keyword

I have taken a reference from the msdn site to clearly demonstrate the use of new keyword

public class A
{
public virtual void One();
public void Two();
}
public class B : A
{
public override void One();
public new void Two(); }
B b = new B();
A a = b as A;
a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B

See the Access modifiers

Following are the types of access modifiers available

public: Access is not restricted.

protected: Access is limited to the containing class or types derived from the containing class.

Internal: Access is limited to the current assembly.

protected internal: Access is limited to the current assembly or types derived from the containing class.

private: Access is limited only to the containing type.

What is an assembly?

An assembly is basically a compiled code of the logical steps.Examples are .dll (Dynamic link library) ,.exe(Executables) etc

How to create an Assembly?

Creating single file and multi file assemblies.

Creating an assembly Interface

We know that C# doesn’t allow a derived class to have more than one base class.But a class can we derived from multiple interfaces.

An interface is a contract that the class will going to implement in its own way.This is looking difficult to grasp but let us see the example first

Examples

Example 1

using System;

interface MyInterface
{
void ShowonConsole(int a,int b);
}

class MyClass : MyInterface
{
public void ShowonConsole(int a,int b)
{

Console.WriteLine(“a + b ={0}” ,a+b);

}

}

class Program
{
static void Main()
{

MyClass obj = new MyClass();

obj.ShowonConsole(2,2);

}
}

Example 2

using System;

interface MyInterface
{
//Property without implementation
int PassengerNumber
{
get;
set;
}

//Property without implementation
string PassengerName
{
get;
set;
}
}

// Interface implementation
class MyClass : MyInterface
{
int _passengernumber;

// Implementation property
public int PassengerNumber
{
get
{
return this._passengernumber;

}
set
{
this._passengernumber=value;

}
}

string _passengername;

// Implementation property
public string PassengerName
{
get
{
return this._passengername;
}
set
{
this._passengername = value;
}
}
}

class MyClass2 : MyInterface // Interface implementation
{

public int PassengerNumber // Property implementation
{
get;
set;
}

string _passengername;

public string PassengerName // Property implementation
{
get
{
return this._passengername;
}
set
{
this._passengername = value.ToUpper();
}
}
}

class Program
{
static void Main()
{
MyInterface Class1 = new MyClass();
MyInterface Class2 = new MyClass2();

Class1.PassengerName = “John”;
Class1.PassengerNumber = 1241;
Class2.PassengerName = “Smith”;
Class2.PassengerNumber = 3457;

Console.WriteLine(“MyClass1 Passenger number={0},name={1}”,Class1.PassengerNumber,Class1.PassengerName);
Console.WriteLine(“MyClass2 Passenger number={0},name={1}”, Class2.PassengerNumber, Class2.PassengerName);
}
}Multiple Interfaces in a class

A class ‘A’ implementing multiple interfaces I1,I2,I3 can be written as

class A:I1,I2,I3

{

//Implementation here

}

The most common use of interfaces is to hide the implementation of classes etc.Code reusability,maintainability, and extensibility

Interface Vs Abstract Class

Multiple interfaces can be implement in a class but multiple abstract classes can not be used as base class of a single derived class.

Both can not be instantiated but abstract class can contain code.Interface does not have anything besides definitions

Note:There are no access modifiers applied to the interfaces

Inheritance in Structures

Structures do not support inheritance.Here is a link which clearly demonstrate this

http://stackoverflow.com/questions/2310103/why-a-c-sharp-struct-cannot-be-inherited

Note: Avoid implementing interfaces with structures.As structure is a value type and the interface is a reference type.This will involve lots of boxing and unboxing jargon which is not a good programmer’s choice as far as coding and memory management is concerned

Structure using properties and implementing an interface

Example 1

Taken from
http://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx

using System;

struct SimpleStruct
{
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
{
xval = value;
}
}
}
public void DisplayX()
{
Console.WriteLine(“The stored value is: {0}”, xval);
}
}

class TestClass
{
public static void Main()
{
SimpleStruct ss = new SimpleStruct();
ss.X = 5;
ss.DisplayX();
}
}

Output

The stored value is: 5

Refer:

Structure implementing an Interface

Passing Class and Structure in method argument

Read an understand example 2 from the link.It is quite easy

 

Enums

Enum declares an enumeration.A very good thing about an enumeration is the fact that we can give our desired names to the data types

Example

using System;

class Program
{
/*Enumeration list consisting of user-defined names of int data types
Every enumeration list must have all the enumerations of the same type

*/
enum MyValues
{

Boom=1,
Bang=2,
Crash=3

};

static void Main()
{

MyValues enumval1 = MyValues.Boom;
MyValues enumval2 = MyValues.Bang;
MyValues enumval3 = MyValues.Crash;

Console.WriteLine(“Constant enumerationsn”);
Console.WriteLine(enumval1);
Console.WriteLine(enumval2);
Console.WriteLine(enumval3);

Console.WriteLine(“nEnumerations valuesn”);
Console.WriteLine((int)enumval1);
Console.WriteLine((int)enumval2);
//this is legal
Console.WriteLine((double)enumval3);

}
}

Output

Constant enumerations

Boom
Bang
Crash

Enumerations values

1
2
3

The param and base keywords

Use of base keyword

The param Keyword

So we have reached the end of the topic Classes, Inheritance, Interfaces, Structures and Enums

Lesson 4 completed….

Copyrighted.com Registered & Protected 
3LLX-TABF-2XTA-OHFN


Syed Adeel Ahmed
Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.