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: C#3.0, Object oriented programming, OOP
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.
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.
Thank’s for sharing information, coincidences have information that I need in your posts
Very helpful article, i bet even experience develoeprs might not know this all… good logic implementation.
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
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.
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.
very good post. it clearly explained the OOPs concepts in a precise manner.
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 .
Clear and easy. Thank you.
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.
Good article easy way to understand the OOPs consepts.Thanks a lot.
It is very good article.Its helps me a lot.
Could you please send me the source code.it would be highly appreciated
its really very nice article.i learned more knowledge on oops concept.
Thank U
Really super article ever i have seen about OOPS concept. Good work… I want source code please. Thank you.
Good
thank u very much i struggle for long time to learn oops concepts at last i got good concepts
Its really very nice. Thank u for u wonderful help.
Thanks a lot,This article helped me a lot in understanding oops concepts in asp.net.Its very nice
Hi
would like to know the source code..please send me.
Thumbs up for your post.
Thanks its really good article to understand the oops concept
Yes Praveen Really its a good artical.
This is very nice. Thank u for your post
its good and helpful
Hi bro it is simply super really i got good knowledge about oops concepts after i pratise with ur examples
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.
good….
Thanks a lot ,it is good one…..
thanks a lot
Easy to understand. Good work
Its really helpful and nice article. Can you please email me the source code ?
Can u send me one complete application which implemented all oops concepts…
please send me oops in c#.net source code with example programs . bathala.ramesh430@gmail.com this is my mail ID.
Thank you.
If you please I need the source code (megosoma@yahoo.com)
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.
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 :-)
Thanks Sir,Its really helpful and nice article.Easy to understand.please send me oops in c#.net source code with example programs…….
THIS IS GOOD TO LEARN FASTER
PLEASE EMAIL ME THE SOURCE CODE
Nice Article , Really it helps me a lot..
the topics like interface,delegates,events and oops are very easy to understand..
Nice article..
Explanation and comments are beautifully done…
Need source code,kindly mail it to me on bhushan_salaskar1987@yahoo.com
i know how much effort u have taken to complete this oops concept article.
Thanks for your BIGHEARTED WORK
thanku so much….
Nice article…helped me to get a basic idea about the world of OO programming. Thanks :-)
Hi… Thankyou… very much.. it’s through i learned of lots.
Its helped me lot…thank you.. Please email me the source code. My email: ramkotari@gmail.com
Nicely explain the oops concept with simple example,Thanks a lot for great article,please forward me the source code
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
gr8 work..Very useful to understand with real time examples.
Can you please send me the source code to my mail
Dear Sir,
I am vijendra yadav. I am so thankful for Your valuable statement about Object Oriented programing. your article is great .
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
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.
nice article to understand the OOPs concepts. thank you very much. Can I have source code please
Really helpfull to understand oop’s concept with example..Thaanxxxx……
Thanks a lot for this simple and good article.
It is very easy to understand and very useful. Thank u
Thanks a lot…….
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.
its nice………
plz send the source code.
its nice…
Can u please send me sample source code of oops concept
Very Nice Article…Thanks for sharing your knowlege
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
Thanks
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 :-)
Thanks for shairing your knowledge
Thank you so much for sharing this knowledge so beautifully and easily with example…
Really a great article….
Very helpful to every programmer…
Dear Sir ; Thanks for your nice post ; Please provide me full source code regarding OOPS concept and generics
Kind Regards
sir this is best way to learn oops concept thnx sir
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…
It is one of the excellent article for understanding the OOPs concepts in right way.
Thank you so much :)
thanks for the article Can u pls mail me the source code to my mail ID ark_radha@rediffmail.com
It is very useful for people like me to make a start in asp.net
please send me mail regarding this
thanks for sharing information really it is very useful plz send the source code to nannuri87@gmail.com
It is very helpful article for me.please send the source code to my id pundhirssandeep@gmail.com
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 .
Great article for beginners. Thanks.
please sen me the code also ..
very thank for your sharing information details of this artical
Very good topic. I liked it.
Please send me source code
Thanks its really helps to me
Thanks please give source code
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
Thanks a lot for your kind words!!!
send code source code examples to shashidhar.bec@gmail.com
Your Post Is Best Post Out Of All I’ve Seen..Thank U..It Helped Me a Lot!!!
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
Really this Is so good to understand abt OOP’s………………………Thanks for solving my problems in OOP’s
Really useful post…
Please mail me the source code to my id pintoopink@yahoo.com
Nice Article…..Plz email the source code on swati.hake@gmail.com
i could clearly understand what is basic form this,so for thanks
please mail me source code
Very nice and very usefull.
please send some coding examples to my email id appi.tallapu@gmail.com
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.
Hi, Your article is very good,Please Mail me (galleeandfarel@gmail.com) the source code, it would be very helpful for study….
Nice
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
HI
This is great note for object oriented programming in asp.net
Please Mail me the source code, it would be very helpful for study….my id is (imrankhankiu@gmail.com)
[…] 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 […]
nice article ,please send me the source code.
well explantion…
thanx
nice article…best oops article i have ever read…!!
This blog is very good for fresher
It’s really nice.Can you explain casting concept with a clear example?”Convert Base Type to Derived Type” –>Need some explanation regarding this?..
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#…??
its very nice can u explain about asp.net life cycle
Thanks
Hey it’s good article to read, thanks.
It’s very nice……Can u send the source code for this?
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?
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 ….
Really too gud article
very useful article and very easy to understand…thanks a lot
Gooooooooooood …. Realy Good Explanation
This is really really GOOOOOOOOOOOOOOOOOOOOOOOOOOD One.
Thank You so much
thank you very much sir, it help me a lot . please send the source coding
That’s what I call a nice explanation, very clear and concise, well done. Thank you for your effort.
Its Nice Article Sir
please send me mail regarding this
Wonderfull Article I had ever
Very Nice Article… Great thought…
very useful article hanks a lot..
Very good post. I will be facing some of these issues as well.
.
nice article. Can I have source code please
can u able give real time example application using c# program
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 .
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