jump to navigation

Object Oriented Programming Concepts with C#3.0 June 21, 2009

Posted by fofo in asp.net, C#, c# 3.0, Visual Studio 2008.
Tags: , ,
trackback

In this blog I try to write about all the latest issues regarding the .Net platform.

But in this post I will try to explain thoroughly the Object Oriented programming model-paradigm.

Speaking from my experience so far, I have identified that the lack of knowledge of basic-advanced OOP concepts is the main reason that people fail to grasp how to design and implement a .Net application.

Dragging and dropping controls from the Toolbox to an .aspx page and connecting to a database does not mean we know OOP.

Unless you do have a good knowledge of OOP concepts , there is a pretty good chance you will fail in your projects.

In this very long post I will try to explain in details the OOP concepts using C# 3.0 in an ASP.NET application.

Many good people have created very good tutorials which are available on the internet about OOP , but I thought I will have a go myself.Along the way I will show you tips and tricks with do’s and dont’s.

Well, some people think, “I do not need classes and object oriented programming to develop my applications”.

That is a true. However if you want to create .NET applications you must use objects. Even if you fail to realise it, everything in .Net is an object. When you open a connection to a database that “connection” is an object. To put it in one line:

Each class in C# is automatically (implicitly) inherited from the Object class.

I have been posting about C# 3.0 new features in other posts and there will be links where required.

Some of the topics-concepts, I will try to cover are:

  • Classes
  • Properties
  • Methods
  • Fields
  • Members
  • Enums
  • Casting
  • Structures
  • Abstraction
  • Encapsulation
  • Interfaces
  • Static classes
  • Constructors
  • Method overloading
  • Inheritance
  • Overriding methods
  • Virtual methods
  • Abstract classes
  • Polymorphism
  • Delegates
  • Events
  • Assemblies
  • Namespaces

and many more…

Before jumping into bits of code and create our step by step example, I must explain some basic concepts regarding  OOP.

  • What is a class?

A class is an abstract concept. It is a blueprint. Try to think of a class as e.g  the blueprints of a car in the real world.

The designers of auto mobiles sit in front of their computer (or use paper and pencil) and describe exactly the parts of the auto mobile. They describe how these parts interact, the colour of the car, the height of the car, the size of the engine, the acceleration of the car, if the car has air-conditioning system installed.

Then the mechanics that observe the production line, make sure that the cars built (the actual cars) follow the blueprints outlined in the design stage of building a car.

So a class is a way of describing real world entities. It is the code definition for objects.

The class is the fundamental building block of code when creating object-oriented software. A class describes in abstract (in theory) all of the characteristics and behaviour of an object.

The object on the other hand is the instance of a class. The real thing, if you excuse my slang…

So we must start thinking about modelling our applications in terms of objects.

When someone, who has hired us to implement a web site-commerce site for his business, he could outline his view of the web site in plain words…

” I would like to have a site where I can keep track of the sales-orders that were placed through the site. I also would like to be able to see the customer details and manage my employees details”,

Then you must think in terms of Orders,Customer,Employee classes-objects for this particular scenario.

This is a first attempt of Abstraction for the scenario above.

Abstraction is the process of representing simplified versions of real-world objects in your classes and objects.

Programming with the OOP paradigm is to decide what a class should represent and breaking down your code into a group of interrelated classes.

Members of a class

The first thing after finalising the class names is to identify the members of a class.

I will talk about Properties, methods and events. As we go on I will talk in greater detail about class members.

  • What is a property ?

A Property allows you to access an object’s data. Properties can be read-only, so they cannot be modified, while others can be changed. A Property defines the state of an object.It describes its individual data or unique configuration.

  • What is a method ?

A method allows you to perform an action with an object. Unlike properties, methods are used for actions that perform a distinct task and may  change the object’s state-property.

  • What is an event ?

An event provides notification that something has happened. Objects can fire events to trigger the code we have placed in the event-handling routines-methods. For example, if a user clicks on a button,the button object fires a Click event, which our code can react to.

Methods, properties and events can be considered as the public interface of a class.

Now we are ready to move on and practice what we have been saying so far.

I assume that people who will read this post, have some experience with C# and Visual studio as a development platform.

I will use Visual Studio 2008 Professional edition. People who have downloaded and installed Visual web developer 2008 can also follow these examples. You can download Visual Web Developer by clicking here .

I will create an ASP.NET application. I will create a base class and then take it from there and try to highlight all the concepts mentioned above. The point of this example is not create super sophisticated classes and methods but to create a simple class with plain properties and methods.

1) Launch VS 2008

2) Go to File->New->Project

3) From the templates, choose ASP.NET web application. Make sure you select C# as the language of development

4) Give a name for your project. I name it “LearnCLass”. Click OK on the Templates window.

5) You will have 2 main files, Default.aspx and Default.aspx.cs

Building a basic class

The class I will construct regards a Person class.This class can represent any person, e.g the customer of an e-commerce shop.The Person class will store the person’s data, and it will include the built-in functionality needed to generate a block of HTML that displays the person details on a web page. We will test this class with an ASP.NET page.
Once you’ve defined a class, the first step is to add some basic data. The next example defines five member variables that store information about the person, namely, its name, surname, age, height,weight .

In your default.aspx.cs (code behind file) you have something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{

Then add the class definition

public class Person
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;
}

Now we have the class definition we need to creating an object. We must use new keyword to do that. The new keyword instantiates the object, which means it creates a copy of the class in memory. If you define an object but don’t instantiate it, you’ll receive an error from the compiler.The members of a class (methods and properties) are accessed using dot ‘.’ operator against the reference of the object.

In the Page _Load event handling routine type

protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson;
mynewperson=new Person();
mynewperson.name = “nikos”;
mynewperson.surname = “kantzelis”;
mynewperson.age = 31;
mynewperson.weight = 88;
mynewperson.height = 1.78M;
Response.Write(mynewperson.name);
}

Run your application by hitting F5 from the keyboard and see the results.

What I am trying to highlight here, is how to create an object from a class.The bit that does it is this:

Person mynewperson;
mynewperson=new Person();

One could write it in a single line

Person mynewperson=new Person();

But the snippet of code inside the Page_Load method is not very well thought.

One could write mynewperson.age = -2;

We would not like to have the code above. The reason the code above works is that the properties of the Person class,

are all public. That is the visibility of the properties is public. Another more technical word for visibility is scope.

This is very important concept and one must understand.

The main accessibility keywords are

public -Members defined as public can be accessed by any other class
private – Members defined as private can be accessed only by code procedures inside the current class
internal – Members defined as internal can be accessed by code procedures in any of the classes in the current assembly (the compiled file)
protected Members defined as protected can be accessed by code procedures in the current class or by any class
that inherits from this class

So by having in our example the variables defined as public, this means that any other class or method of another class has direct access to those variables-properties.

We must not design classes like that. In order to have useful classes we must have a way to protect the data within them. This is called, Encapsulation. Encapsulation is is the hiding of the internal mechanisms and data of a class behind a defined interface.Other classes , if they need to “talk” – interact with a specific class, they can do so by just knowing its interface. Let me try to explain this better with my car analogy example. When you try to change the gear in your car, imagine the gear system as class or a component, the gear system interacts with another system that commands the car to slow down or accelerate. The gear system does not have to know how it is done, just how to interacts with it.

So let’s change public to private.

private string name;
private string surname;
private int age;
private decimal height;
private decimal weight;

Let’s run the code again. We get the following error. I am sure you get what is going on here. There is no variable name still “alive-visible” when we call it in the Page_Load event handling routine.

Error    1    ‘LearnCLass._Default.Person.name’ is inaccessible due to its protection level    C:\Users\fofo\Desktop\webapps\LearnCLass\LearnCLass\Default.aspx.cs    24    25    LearnCLass

In general objects are automatically released when the appropriate variable goes out of scope. Objects are also released when your application ends. That means that their memory is reclaimed. In the managed applications, the CLR uses a service (garbage collector) that periodically scans for released objects and reclaims the memory they hold.

So , you must be thinking that we have not accomplished anything yet. The truth is that we have not finished yet.

We must write property accessors for the member variables.

For the name member variable we have

public string Name
{
get
{
return name;
}

set
{
name = value;
}

}

With C# 3.0 we had a new feature that is called Auto-implemented properties. Have a look here in one of my past posts to find out more about that.Basically with auto implemented properties,  there is no need to implement a private field to store the value.

So we could write the code above like this

public string Name { get; set; }

much easier isn’t it?

We can do that for all property accessors if no no additional logic is required.

So we have

public string Name { get; set; }
public string Surname { get; set; }

that means that we can comment out the following lines from our class declaration.

//private string name;
//private string surname;

but for the Age,Height,Weight member variables we require some additional logic for the property accessors.

Just for this example let’s just assume that a person’s age must between 1 and 100, his height from 1 to 2.40 and his weight from 30 to 240.

public int Age
{
get
{
return age;
}

set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}

age = value;
}

}

public decimal Height
{
get
{
return height;
}

set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}

height = value;
}

}

public decimal Weight
{
get
{
return weight;
}

set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}

weight = value;
}

}

When trying to assign an invalidvalue, an exception is thrown by the class code.

Now let’s create a method for our Person Class.

We can create a very simple method like:

public void Talk()

{

// add logic later

}

or we can add a method that returns something (it is not void) and can do something useful.

So we can have a method that calculates the age of the person in years. The method follows:

public int CalculateAge(DateTime birthDate)
{DateTime now = DateTime.Today;int years = now.Year – birthDate.Year;if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;return years;
}

It is not something difficult.  We should not focus on how the method does it, right now. Basically I am just using

DateTime Class in the System namespace.

In your Page_Load event you can add to the code already there, the following bit

string myDateTimeString;int res;myDateTimeString = “17 Feb,1977”;DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);Response.Write(res.ToString());

Run your application and see the results.

The Person class so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnCLass
{
public partial class _Default : System.Web.UI.Page
{

public class Person
{
//private string name;
//private string surname;
private int age;
private decimal height;
private decimal weight;

public int Age
{
get
{
return age;
}

set
{
if (value < 1 || value > 100)
{
throw new Exception(“Invalid age”);
}

age = value;
}

}

public decimal Height
{
get
{
return height;
}

set
{
if (value < 1.00M || value > 2.40M )
{
throw new Exception(“Invalid height”);
}

height = value;
}

}

public decimal Weight
{
get
{
return weight;
}

set
{
if (value < 30 || value > 240)
{
throw new Exception(“Invalid weight”);
}

weight = value;
}

}

public string Name { get; set; }
public string Surname { get; set; }

public int CalculateAge(DateTime birthDate)
{

DateTime now = DateTime.Today;

int years = now.Year – birthDate.Year;

if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
–years;

return years;
}

public void Talk()
{
//add logic later
}

}

protected void Page_Load(object sender, EventArgs e)
{
Person mynewperson=new Person();
mynewperson.Name = “nikos”;
mynewperson.Surname = “kantzelis”;
mynewperson.Age = 22;
mynewperson.Weight = 88;
mynewperson.Height = 1.78M;
Response.Write(mynewperson.Name);
Response.Write(“</br>”);
Response.Write(mynewperson.Surname);
Response.Write(“</br>”);
Response.Write(mynewperson.Age);
Response.Write(“</br>”);
Response.Write(mynewperson.Height);
Response.Write(“</br>”);
Response.Write(mynewperson.Weight);
Response.Write(“</br>”);
mynewperson.Talk();

string myDateTimeString;

int res;

myDateTimeString = “17 Feb,1977”;

DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
res=mynewperson.CalculateAge(dt);

Response.Write(res.ToString());

mynewperson.Talk();

}
}
}

When we create our Person object,

Person mynewperson=new Person();

you might think that we have here is a method call.When an instance of a class is created the C# system makes a call to a constructor method in that class. A constructor is a function with the same name as that of the class. Every single class must have a constructor method.It is called when we write the new keyword. Even If we do not provide a constructor method, the compiler creates a default one,without any parameters.

So in our case is:

public Person()

{

}

We often need to overload our default constructors. Let me explain what overload is.

It is possible to have more than one method with the same name and return type but with a different number and type of arguments-parameters. The compiler knows every time which method to call by looking at the number of the arguments. I will explain more about overloading later on.

Sometimes it is better to send some information to the class upfront so it is available as soon as it is constructed. So let’s overload the default constructor.

public Person( string thename, string thesurname, int theage)
{
Name = thename;
Surname=thesurname;
Age = theage;
}

We can also have a destructor.Destructors are just the opposite of constructors.

It has the same name as the containing class but prefixes it with the ~ (tilde) sign.

It is called automatically when the object is about to be destructed (when garbage collector is about to destroy your object).

It has no return type just as the constructor does not have one as well.
We declare the destructor in our case like

~Person()
{
// place our e.g resource freeing code here
}

What really happens is that the C# compiler internally converts the destructor to the Finalize() method.

The Object class is the parent of all objects in .Net.It contains a method called Finalize().
This method is  be called when your object is garbage collected . One can override this method and put here code for freeing resources that you reserved when using the object.

protected override void Finalize()
{
try
{

// put some code here
}
finally
{
base.Finalize();
}
}

Do not worry about the override keyword. I will explain it later on.

Many people ask me about enums and structures and what they are and how we can use them.

What is enum?

An enumeration is a group of related constants. Each constant is given a descriptive name.
Every enumerated value corresponds to a preset integer.

Sometimes we want to hold a range of particular values or states. This is a perfect place to use enums.

In our example we could have something like

public enum PersonState
{
Married = 1,
Widoewed = 2,
Single = 3,
Divorced = 4
}

And then call it from our Page_load event

PersonState personstate;

personstate =PersonState.Married;
Response.Write(“</br>”);
Response.Write(personstate);

C# compiler will  represent these states as particular numeric values . But it will do so behind the curtains.

So I can use the enum name values and have more readable code. The concept of enumerated values is extremely important, because the .NET class library uses it extensively.

What is a structure ?

Structures are lightweight objects. Structures are very similar to classes in C#.

Basically they can hold a collection of different things about a particular item.

They are denoted in C# by the struct keyword. In our example we could have a structure like this

struct NewPerson
{
public string name;
public string surname;
public int age;
public decimal height;
public decimal weight;

}

In the Page_Load event routine we can have

NewPerson myperson;

myperson.name = “John”;

Response.Write(myperson.name);

As you notice there is no need for the new keyword.

There is a key difference between objects and structures. Structures are managed in terms of value while objects are managed in terms of reference.

A reference holds the physical address of where the data is stored in memory. So it points to the data. It is not the actual data. On the other hand structure variables hold the actual data.

There are some limitations with structures and even if they have their place when we design a software component, they can never be used to replace a class type.

A structure  for example can neither inherit another class, nor can they be inherited. A structure can implement interfaces.

A common place where we find structures  are Net framework types like System.Int32, System.Double , System.Boolean.If you want to check it out yourselves just place the pointer of your mouse on an int declaration and right click. From the right-menu click on the “Go To Definition “. Then you will see the definitions. See the picture below.

go to def

Inheritance

I know a lot people who use Inheritance in their applications without even realizing.

If you look at the Default.aspx.cs you can see

public partial class _Default : System.Web.UI.Page

In plain English , this means that every web page we create is a child of the Page class. Inheritance is a form of code reuse. It allows one class to acquire and extend the functionality of another class. There is no need to reinvent the wheel when other people have done this for you. Instead of that you have only to think about the peculiarities of the project at hand.

Let’s assume that we need to create another class,called Student.

In this class we want to inherit the functionality of the Person class or base class.

class  Student : Person

Then we want to extend the Parent class. We want to create a new simple method to calculate the total marks achieved by the student.

The whole Student class follows. I have explained in detail properties and methods in previous paragraphs.

class  Student : Person
{
private int _marksEnglish;
private int _marksLiterature;
private int _marksIT;
private int _marksMaths;
private int marksTotal;

public int marksEnglish
{
get
{
return _marksEnglish;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}

_marksEnglish = value;
}
}
public int marksLiterature
{
get
{
return _marksLiterature;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksLiterature = value;
}
}

public int marksMaths
{
get
{
return _marksMaths;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksMaths = value;
}
}

public int marksIT
{
get
{
return _marksIT;
}
set
{
if (value < 0 || value > 20)
{
throw new Exception(“Invalid number”);
}
_marksIT = value;
}
}

public int CalculateTotalMarks()
{

marksTotal = marksEnglish + marksLiterature + marksIT + marksMaths;

return marksTotal;
}
}



In our Page_Load event , we can create a new object of type Student.

Student mystudent = new Student();
Response.Write(“</br>”);
mystudent.Name=”fofo”;
Response.Write(mystudent.Name);
mystudent.marksEnglish = 12;
mystudent.marksLiterature = 13;
mystudent.marksIT = 18;

mystudent.marksMaths = 17;

mystudent.CalculateTotalMarks();


Response.Write(mystudent.CalculateTotalMarks());

If you pay attention even though we did not define the Name and Surname properties for the Student class, they are available to the class, since they are inherited. The same applies for the CalculateAge method.

Some things worth mentioning regarding inheritance are:

  • C# allows only single class inheritance
  • Multiple inheritance of classes is not allowed in C#
  • The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# and the .NET framework
  • A class may implement multiple interfaces. We may also declare objects of different classes in a class. This way, the encapsulated class may be instantiated in other classes.

Now, we know how to make a new class based on an existing one and extend it.If we want to change the behavior of a method in the base class in the child class we must override it.

Let’s create a new method in the base class (Person) that we want to override it later on the child class. It is just a method that calculates the pay of a person.

public double CalculatePay(double hoursWorked, double wageperhour,double tax)
{

return (hoursWorked * wageperhour * tax);
}

This method is inherited in the Student class. Let’s assume that we live in a fantastic world where student’s money is not taxed if the student worked less than 100 hours.

The first thing to do is to add the word virtual to the CalculatePay method.So we have:

public virtual double CalculatePay(double hoursWorked, double wageperhour,double tax)
{

return (hoursWorked * wageperhour * tax);
}

and then to use the word override in Student class CalculatePay method

public override double CalculatePay(double hoursWorked, double wageperhour,double tax)
{
if (hoursWorked > 100)
{

return (hoursWorked * wageperhour * tax);
}
else
{
return (hoursWorked * wageperhour);

}
}

From our Page_Load event we can call this

Response.Write(mystudent.CalculatePay(45, 4, 0.45));

By calling the line above the CalculatePay method of the student class will be invoked.This relationship between virtual  methods and the derived class methods that override them enables polymorphism.

If we want to stop overriding a class we can use the special word sealed. This means that this class cannot be used as the basis for another class.

if you change the

public class Person to public sealed class Person

and run your application you will receive an error

cannot derive from sealed type ‘LearnCLass._Default.Person

Now it is time to see in greater detail method overloading.

In our Person class we can define a new method

public string JoinNames(string name, string surname)
{
return name + ” ” + surname;
}

Now we could have a different implementation of the method above.

public string JoinNames(string prefix, string name, string surname)
{
return prefix + ” ” + name + ” ” + surname;
}

In our Page_ Load event if we write the line:

mynewperson.JoinNames(“Mr”,”nikos”, “kantzelis”)

The compiler will not complain. It will know which method to invoke depending on the number of the parameters-arguments it “sees”.

Polymorphism (from the Greek meaning “having multiple forms” – “Poly” means many and “morphy” means “shape”) can be achieved by overloading a method.

What is a static class?

In .NET we can  use some class members without creating an object first. These are called static members, and they’re accessed by class name. So far in the previous examples we have seen the static property DateTime.Now to retrieve a DateTime object that represents the current date and time. We didn’ create a DateTime object first.

If we wanted to have a method that determines whether a person can hold a valid driving licence, the method would look like this.

public bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}

}

The method above is a good candidate to become a static method.In order to do that, we just add the word static

public static bool AllowedToDrive(int age)
{
if (age >= 18 || age <= 80)
{
return true;
}
else
{
return false;
}

}

In our Page_Load event routine,we can write

Person.AllowedToDrive(22)

As you see we do not need an object to invoke our method, just the class name.

So a static member is a member of the class and not a member of an instance of the class.

It takes some experience to determine which methods or classes. One common place where we find static classes and methods is the creation of libraries that provide general functionality, e.g find the square root of a number, find the perimeter of a circle.

The next thing to review is Interfaces. I will not cover Interfaces in detail because you can find another post of mine on Interfaces on this blog.

The Interface is basically a contract between a the Interface and a class. In the Interface we do not have implementation of properties of methods.

The class that implements the Interface or inherits from the Interface must implement the methods defined in the Interface.

A .NET interface is similar to an abstract class in the sense that it’s a kind of a template. More on abstract classes later.

If we define an interface like this

interface IPerson
{
double DaysVacation(int yearsOfWork);
}

and if we say that the Person class implements the IPerson Interface

class Person : IPerson

the Person class must in its body implement the DaysVacation(int yearsOfWork) method.

public double DaysVacation(int yearsOfWork)
{

if (yearsOfWork > 25)
{
return 25;
}
else if (yearsOfWork < 25 && yearsOfWork > 20)
{
return 20;
}
else
{
return 10;
}

}

What is an abstact class?

If we need to provide common fields and members to all subclasses, we create an Abstract class. We can create an abstract class, with the use of the abstract keyword. Abstract classes cannot be instantiated. In our example if we decide that there are some things that an object of type Person must do, then we can make the class Person abstract and then get the clild classes to provide the implementation. I will create another class to demonstrate abstract classes, because we need to change los of code in the Person class  and I do not want to do that.

In abstract classes we can have abstract members and virtual members. An abstract member is not implemented in the base class and must be implemented in derived classes in order for the class to compile. A virtual member must be implemented in the base class, and if need be (optionally) overriden in the derived class if want the child method to do something different.

Let’s define our abstract Vehicle class.

public abstract class Vehicle
{

public string Model { get; set; }
public string Color { get; set; }
public int NumOfDoors { get; set; }
public int NumoOfWheels { get; set; }

public Vehicle(string model, string color)
{
this.Color = color;
this.Model = model;

}
public abstract string Accelarate(int speed);

public virtual double CalculatePetrolCostPerDistance( double distance)

{
double costperkilometer=0.25;
double res;

res = distance * costperkilometer;

return res;
}

}

Now we can have another class Car that can inherit from the Vehicle class. The method Accelerate in the Vehicle class must be implemented in the child class.

public class Car : Vehicle
{

public Car(string model, string color): base(model,color)
{
//code to be added
}

public override string Accelarate(int speed)
{
return “I can accelerate. My speed is right now:”+speed.ToString();
}

public override double CalculatePetrolCostPerDistance(double distance)
{
double costperkilometer = 0.45;
double res;

res = distance * costperkilometer;

return res;
}

}

We can create and use an object type Car in our Page_Load event handling routine

Car mycar = new Car( “bmw”, “silver”);
Response.Write(mycar.Accelarate(134));
Response.Write(“</br>”);
Response.Write(“The cost is: ” + mycar.CalculatePetrolCostPerDistance(125.5).ToString() +” euros”);

In the child class I have implemented a simple version of the Accelarate method by using the override keyword and I chose to ovveride CalculatePetrolCostPerDistance. But If i did not need any different behaviour for the CalculatePetrolCostPerDistance then that would be ok, my class would compile just fine.

Abstract classes are a lot like interfaces, however abstract classes are different in that they contain fully implemented methods alongside the abstract ones.So we do not have to implement the same methods in each of the components that implement a particular interface. An abstract class can contain fields, constructors, or destructors and implement properties while an interface cannot.
An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.

What is a delegate?

For more information on this topic have a look at this post of mine.

What is Generics ?

Same applies here. I have another single post on Generics and I do not see any point repeating myself.

What is a namespace?

In my solution in the Default.aspx.cs , I have the namespace LearnCLass namespace. All my classes and code is included in this namespace.

Namespaces are a logical way to group classes. Let me give you an example of what it means. It is a way that we can identify a class beyond doubt.

Imagine that you want to phone an old friend that you have lost track, so you can invite him to your wedding. So you phone the phone directory service.

Your friend’s name is George Patouxas. The operator lets you know that there are 100 people with this name coming up. Then you tell the operator that his mother’s name and father’s name are Maria and John respectively. BINGO!! The operator tells you there is only match. So in our example the LearnCLass.Person class resides in this specific namespace and if someone wants to use it, he can use the using LearnCLass.Person declaration.

That is exactly why namespaces are for in .NET.  We try to group related classes in namespaces and all of them that reside in this particular namespace will be uniquely identified.

If I have a class called Calculate in my LearnClass namespace, then there will be no conflict if need be to use another component from a third party that has also a Calculate Class.

That Calculate class will reside in the AnotherNameSpace so there will be no conflict.

Please note that in the beginning of the Default.aspx.cs we import namespaces that we need to using System.Web.UI;

Assemblies

All .NET classes (built-in or custom made) are contained in assemblies. Assemblies are the physical files that contain compiled code. Assembly files have the extension .exe if they are stand-alone applications or .dll if they’re reusable components. Assemblies are a physical package for distributing code. Often, assemblies and namespaces have the same names. For example, you’ll find the namespace System.Web in the assembly file System.Web.dll.

But in many cases there is no direct mapping between assemblies and namespaces.

What is Casting?

When we talk about casting, we can think of this concept in terms of narrowing and widening. If you move a value from one type to another that narrows the value, it will ask you to explicitly do it yourself. When you move a value from one type to another by widening it, it does not complain.

By widening I mean that if I have the declaration:

int mynum=5;

float anothernum=mynum;

This will be fine because the floating point type can hold all the values supported by the integer type.

If I have this statement (narrowing)

double mynum = 3.5;
float thenum = mynum;

the compiler will complain.

Cannot implicitly convert type ‘double’ to ‘float’. An explicit conversion exists (are you missing a cast?)

The compiler is basically saying “Is there any chance you are discarding information?”

But you can cast the value by using this statement.

double mynum = 3.5;
float thenum = (float)mynum;

This is an explicit conversion and I say in simple words to the compiler, that I take the responsibility for the possible data loss.

For reference types, if we have a situation like this, where the derived type (Student) is converted to base type (Person), we have imlicit conversion which is safe.

Student thestudent = new Student();

while if we type this:

Person theperson=new Person();

this will fail and we must explicitly cast it to the Student type, like this.

Person theperson=new Person();
Student thestudent = (Student)theperson;

Hope it helps. If you need the source code, leave a comment and I will email it to you.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Comments»

1. anton - June 22, 2009

Thank’s for sharing information, coincidences have information that I need in your posts

2. Maggo - July 9, 2009

Very helpful article, i bet even experience develoeprs might not know this all… good logic implementation.

3. Shimpli - September 8, 2009

Benefitted by this article a lot and the examples too. But still some confusion in the usage of Interfaces and abstract classes. Anyways thanks a lot

4. Imran Khalid - December 26, 2009

Really a nice article which help me alot to understand classes and related topics. I have still confused about delegates and its usage with events specially. If one could provide me architectural detail with sound expamples that will be a great help. Overall I am pleased to have this article indeed.

5. sreenu - January 7, 2010

Very nice and use full post ,only this article I have seen in the web with detailed information, thank you so much for posting this type of information.

6. vinay - January 19, 2010

very good post. it clearly explained the OOPs concepts in a precise manner.

7. srilatha - January 27, 2010

very very nice post. It really helped me a lot. Thank u very much. I need source code also .

could u please mail me the source code. I’ll be really helpful for that .

8. cristian - February 18, 2010

Clear and easy. Thank you.

9. Ritesh Gupta - March 30, 2010

Very nice article…It really helped me…..Thanks you…I need Source code……
Whether any similar article related to ADO .Net and ASP .Net please forward me.’
Thank you once again.

10. Rahimkhan - April 9, 2010

Good article easy way to understand the OOPs consepts.Thanks a lot.

11. Joby John - May 20, 2010

It is very good article.Its helps me a lot.
Could you please send me the source code.it would be highly appreciated

12. Nagaraju G - June 21, 2010

its really very nice article.i learned more knowledge on oops concept.
Thank U

13. kannathasan T - September 19, 2010

Really super article ever i have seen about OOPS concept. Good work… I want source code please. Thank you.

sowjanya - September 23, 2010

Good

14. siva - October 27, 2010

thank u very much i struggle for long time to learn oops concepts at last i got good concepts

15. Sathy - November 2, 2010

Its really very nice. Thank u for u wonderful help.

16. laya - November 10, 2010

Thanks a lot,This article helped me a lot in understanding oops concepts in asp.net.Its very nice

17. Laya - November 10, 2010

Hi
would like to know the source code..please send me.

18. Maverick - November 13, 2010

Thumbs up for your post.

19. Praveen Agrawal - November 25, 2010

Thanks its really good article to understand the oops concept

Vivek Tiwari - November 25, 2010

Yes Praveen Really its a good artical.

20. Nagamani - November 26, 2010

This is very nice. Thank u for your post

21. sanmati - December 15, 2010

its good and helpful

22. rahul - December 28, 2010

Hi bro it is simply super really i got good knowledge about oops concepts after i pratise with ur examples

23. Vikram Singh Saini - December 29, 2010

Now I have started to believe strongly, “Microsoft Certified Trainer(s) are truly best and they strongly deserve the credit. And you are one of the best MCT of whom blog I have read.

Writing style very simple even (I believe) school level teenagers can easily understand your explained concepts.

Please accept my sincere thanks for your hard efforts.

24. krishna - December 29, 2010

good….

25. suresh - December 30, 2010

Thanks a lot ,it is good one…..

26. abhishek - January 2, 2011

thanks a lot

27. Sagar - January 10, 2011

Easy to understand. Good work

28. Nilesh - January 13, 2011

Its really helpful and nice article. Can you please email me the source code ?

29. Shreeyash - January 25, 2011

Can u send me one complete application which implemented all oops concepts…

30. ramesh - February 8, 2011

please send me oops in c#.net source code with example programs . bathala.ramesh430@gmail.com this is my mail ID.

31. Majdi Al-Shannaq - February 17, 2011

Thank you.
If you please I need the source code (megosoma@yahoo.com)

32. Rekha - February 18, 2011

Its really helpful and nice article. Can you please email me the source code ?
please send me oops in c#.net source code with example programs . rekhas147@gmail.com this is my mail ID.

33. santosh kumar - March 10, 2011

NIce Post please send me the source code . I have one more question in real time when we have to use static class, and abstract class . Just give a simple example it would be great . |Iam learing .net and i have a little bit of coding knowldege.

Hope you will help me out :-)

34. Sonal Mali - March 25, 2011

Thanks Sir,Its really helpful and nice article.Easy to understand.please send me oops in c#.net source code with example programs…….

35. ABHISHEK - April 3, 2011

THIS IS GOOD TO LEARN FASTER
PLEASE EMAIL ME THE SOURCE CODE

36. Sajjad Ali Khan - April 14, 2011

Nice Article , Really it helps me a lot..
the topics like interface,delegates,events and oops are very easy to understand..

37. Bhushan Salaskar - April 18, 2011

Nice article..
Explanation and comments are beautifully done…
Need source code,kindly mail it to me on bhushan_salaskar1987@yahoo.com

38. RAMACHANDRAN - April 19, 2011

i know how much effort u have taken to complete this oops concept article.
Thanks for your BIGHEARTED WORK

39. prashant deep - April 24, 2011

thanku so much….

40. Ali - April 30, 2011

Nice article…helped me to get a basic idea about the world of OO programming. Thanks :-)

41. Pirma - May 3, 2011

Hi… Thankyou… very much.. it’s through i learned of lots.

42. Ram kotari - May 3, 2011

Its helped me lot…thank you.. Please email me the source code. My email: ramkotari@gmail.com

43. Ashish shri - May 23, 2011

Nicely explain the oops concept with simple example,Thanks a lot for great article,please forward me the source code

44. shaikabdulazeem - May 24, 2011

hi,
your article is very nice.thanks a lot.it has helped me in understanding OOP and to others also.can you plz send me sourcfe code to shk.abdulazeem@gmail.com

45. ram - May 26, 2011

gr8 work..Very useful to understand with real time examples.
Can you please send me the source code to my mail

46. Vijendra Singh Yadav - May 30, 2011

Dear Sir,
I am vijendra yadav. I am so thankful for Your valuable statement about Object Oriented programing. your article is great .

47. towheed - June 1, 2011

it is vary nice post.thank you vary mach.could you please send me the source code this is my email id md.towheed@gmail.com

48. hydgirl - June 1, 2011

Very well written article. Thank you so much! I have one thing to point out : In the ‘Casting’ example you have given, this line of code needs to be included :
Person theperson = theStudent ;
You have given the explanation that this sort of implicit casting is allowed but somehow missed giving this line of code.

49. keith white - June 4, 2011

nice article to understand the OOPs concepts. thank you very much. Can I have source code please

50. sumit - June 11, 2011

Really helpfull to understand oop’s concept with example..Thaanxxxx……

51. Esha - June 15, 2011

Thanks a lot for this simple and good article.

52. malathy231984@gmail.com - June 24, 2011

It is very easy to understand and very useful. Thank u

53. Yogesh Pawar - July 5, 2011

Thanks a lot…….

54. Linga Reddy Sama - July 9, 2011

Very nice article about OOPs concepts, i think this article has been covered entire scope of OOPS.
I’m little bit confused about delegates concept, could you please give me elaboration article if you have.

55. rajkumar - July 12, 2011

its nice………
plz send the source code.

56. raman upadhyay - July 24, 2011

its nice…
Can u please send me sample source code of oops concept

57. Dipti Chalke - August 9, 2011

Very Nice Article…Thanks for sharing your knowlege

58. Saravanan - August 17, 2011

Excellent article..
Explanation and comments are beautifully done…
Are you have any material for Generics.. (Pls. send me)
Need source code,kindly mail it to me on saravanan.trainer@gmail.com

59. Sunny Goud - September 2, 2011

Thanks

60. raj - September 4, 2011

Only Intellectual brains can help others in need.
Your Artcle is awesome and pretty informative.
I would rate it 4.5
Thank you and hope the same articles in futures in latest technologies too.
From a friend who is just a beginner in this subject :-)

61. paschima - September 9, 2011

Thanks for shairing your knowledge

62. Nidhi - September 13, 2011

Thank you so much for sharing this knowledge so beautifully and easily with example…
Really a great article….
Very helpful to every programmer…

63. ASHISH DEV - September 14, 2011

Dear Sir ; Thanks for your nice post ; Please provide me full source code regarding OOPS concept and generics
Kind Regards

64. anuj - September 30, 2011

sir this is best way to learn oops concept thnx sir

65. Blue Ray Plus - Latest Technology News - October 7, 2011

Object Oriented Programming Concepts with C#3.0 « DOT NET RULES…

Thank you for submitting this cool story – Trackback from Blue Ray Plus – Latest Technology News…

66. Abdul - October 11, 2011

It is one of the excellent article for understanding the OOPs concepts in right way.

Thank you so much :)

67. RadhaKrishna - October 12, 2011

thanks for the article Can u pls mail me the source code to my mail ID ark_radha@rediffmail.com

68. uday mendon - October 15, 2011

It is very useful for people like me to make a start in asp.net

69. uday mendon - October 15, 2011

please send me mail regarding this

70. balu - October 15, 2011

thanks for sharing information really it is very useful plz send the source code to nannuri87@gmail.com

71. Sandeep Singh Pundhir - October 16, 2011

It is very helpful article for me.please send the source code to my id pundhirssandeep@gmail.com

72. kadiyamramana - October 31, 2011

very very nice post. It really helped me a lot. Thank u very much. I need source code also .

could u please mail me the source code to “kadiyamramana@gmail.com”

I’ll be really helpful for that .

73. Sunil Sharma - November 3, 2011

Great article for beginners. Thanks.

please sen me the code also ..

74. Edukondalu - November 28, 2011

very thank for your sharing information details of this artical

75. Rahul - November 28, 2011

Very good topic. I liked it.

76. Rathiga - December 4, 2011

Please send me source code

77. jyothi - December 8, 2011

Thanks its really helps to me

78. sabeer - December 20, 2011

Thanks please give source code

79. Veerendra Prabhu - December 23, 2011

This Blog is simply superb.. Really appreciate all the time and hard work you have put into this.. this blog was very helpful to me.. Thanks a lot.. i am sure many people have taken great advantage of your post :).. Keep up the good work..

Regards

Veeru

fofo - December 29, 2011

Thanks a lot for your kind words!!!

80. shashidhar.A - January 2, 2012

send code source code examples to shashidhar.bec@gmail.com

81. ranjeeth - January 6, 2012

Your Post Is Best Post Out Of All I’ve Seen..Thank U..It Helped Me a Lot!!!

82. pratikbeheraa@gmail.com - January 9, 2012

wow This Is Awesome………………guys if anyone want to make his oops fundas strong than go through this article…………………………..

please mail me the source code in pratikbeheraa@gmail.com

83. Ruchi - January 19, 2012

Really this Is so good to understand abt OOP’s………………………Thanks for solving my problems in OOP’s

84. pintoo - February 10, 2012

Really useful post…

Please mail me the source code to my id pintoopink@yahoo.com

85. Swati Hake - February 11, 2012

Nice Article…..Plz email the source code on swati.hake@gmail.com

86. Rajarajan - February 12, 2012

i could clearly understand what is basic form this,so for thanks

87. Rajarajan - February 12, 2012

please mail me source code

88. Appi - February 17, 2012

Very nice and very usefull.
please send some coding examples to my email id appi.tallapu@gmail.com

89. JayPrakashSharma - February 28, 2012

Very nice and informative article that beautifully elaborate about OOP’s concept in C#.Net. It helped me lot. I’ve checked another post on OOP’s Concept while I was searching related article over the internet. It also explained very well, please check it at once….

http://www.mindstick.com/Articles/32317070-3dcd-4ca8-9871-56462741028f/?OOP%E2%80%99s%20Concept

Thanks Everyone for your precious post.

90. Anand - March 2, 2012

Hi, Your article is very good,Please Mail me (galleeandfarel@gmail.com) the source code, it would be very helpful for study….

91. kaleem - March 21, 2012

Nice

92. ramesh - March 23, 2012

Hi
IT IS A GREAT STORY OF DOTNET

This is wonderful article for bigginers and who wants learn the pillers of opps concepts in Dotnet

Thank you

93. Uttam - March 25, 2012

HI
This is great note for object oriented programming in asp.net

94. imran khan - March 30, 2012

Please Mail me the source code, it would be very helpful for study….my id is (imrankhankiu@gmail.com)

95. C sharp object oriented programming concepts – C Sharp Programming | Learn Programming » Blog Archive - April 1, 2012

[…] Basic)Programming ConceptsIntroduction to Object Oriented Programming Concepts (OOP) and …Object Oriented Programming Concepts with C#3.0 « DOT NET …Object-Oriented Programming Concepts (Page 1 of 2) :: BlackWasp …Beginning C# Object-Oriented […]

96. srinu - April 3, 2012

nice article ,please send me the source code.

97. evideyo - April 12, 2012

well explantion…
thanx

98. Anurag Tyagi - April 16, 2012

nice article…best oops article i have ever read…!!

99. Ajay Panwar - May 7, 2012

This blog is very good for fresher

100. Arjunan - May 11, 2012

It’s really nice.Can you explain casting concept with a clear example?”Convert Base Type to Derived Type” –>Need some explanation regarding this?..

101. RAHUL Kumar maddheshiya - May 28, 2012

wow it is so nic about us ,when ever i read all the part of OOPs that are clear my all doubts…..
if u dont mind then can u explain thread in C#…??

102. karthik - June 14, 2012

its very nice can u explain about asp.net life cycle

103. sumit - June 16, 2012

Thanks

104. Prasad - June 20, 2012

Hey it’s good article to read, thanks.

105. Lavanya - June 22, 2012

It’s very nice……Can u send the source code for this?

106. kiran - July 5, 2012

Hi It’s a good article to know OOPs concepts from bottom…Can u pls send me all the topic or concepts of OOPs in detail which u mentioned for 3.5?

107. Nisha - July 17, 2012

very much good and easy to understand article…really nice post …Thank you for posting such practical article with good example and less theory part…i think so that we all wanted ….

108. Prabu - August 13, 2012

Really too gud article

109. harika - August 29, 2012

very useful article and very easy to understand…thanks a lot

110. Prashant K - September 5, 2012

Gooooooooooood …. Realy Good Explanation

111. Mahendra Wagh - October 11, 2012

This is really really GOOOOOOOOOOOOOOOOOOOOOOOOOOD One.
Thank You so much

112. kiruthiga ravi - October 21, 2012

thank you very much sir, it help me a lot . please send the source coding

113. marcel - November 21, 2012

That’s what I call a nice explanation, very clear and concise, well done. Thank you for your effort.

114. sakthivel - November 23, 2012

Its Nice Article Sir

115. sakthivel - November 23, 2012

please send me mail regarding this

116. Shamim Ansari - November 24, 2012

Wonderfull Article I had ever

117. Suresh Audi - December 10, 2012

Very Nice Article… Great thought…

very useful article hanks a lot..

118. american tourister boarding bag - February 2, 2013

Very good post. I will be facing some of these issues as well.
.

119. AMIRTHA - February 23, 2013

nice article. Can I have source code please

120. ahmed - April 2, 2013

can u able give real time example application using c# program

121. varunkolanupaka - April 4, 2013

i am happy and lucky to see a post like this ,
It really helped me a lot. Thank u very much. plz send me source code too.

could u please mail me the source code to “varunonline5@gmail.com”
I’ll be really helpful for that .

122. Ashutosh Samantray - May 31, 2013

mail all related oops theory, i am working in .net 4.0, entity frame work, linq to entities, wcf, edmx, winforms, webforms, sql server 2005/2008, c#.net, asp.net, interview question. Abobe releted theories are explained very easily, so mail me all related topics i written. my mail address is ashutoshsamantray6@gmail.com


Leave a reply to siva Cancel reply