Wednesday, February 8, 2012

OOPs Concepts

What is OOP?

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts

In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it. 

What is an Object?

An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address.
In pure OOP terms an object is an instance of a class. 

What is a Class?

class.gif
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.
public class Student
{
}
According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class.
Student objectStudent = new Student();
In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.
In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class

Class members
A class has different members, and developers in Microsoft suggest to program them in the following order:
  • Namespace: The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.
  • Class declaration: Line of code where the class name and type are defined.
  • Fields: Set of variables declared in a class block.
  • Constants: Set of constants declared in a class block.
  • Constructors: A method or group of methods that contains code to initialize the class.
  • Properties: The set of descriptive data of an object.
  • Events: Program responses that get fired after a user or application action.
  • Methods: Set of functions of the class.
  • Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.
Access keywords
Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:

  • Public: Allows access to the class member from any other class.
  • Private: Allows access to the class member only in the same class.
  • Protected: Allows access to the class member only within the same class and from inherited classes.
  • Internal: Allows access to the class member only in the same assembly.
  • Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.
  • Static: Indicates that the member can be called without first instantiating the class.



Sealed class
A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed.
To create a sealed class in C#, the class declaration should be done as:
sealed class Shape 

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

Difference between Struct and Class

  • Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
  • Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
  • Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.
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 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 an Interface?

In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.
Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.
If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.
The sample below will provide an interface for our LoggerBase abstract class.
public interface ILogger
{
    bool IsThisLogError { get; }
}

What is the difference between a Class and an Interface?

In .Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.
If MyLogger is a class, which implements ILogger, there we can write
ILogger log = new MyLogger();
A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.

What is the difference between an Interface and an Abstract class?

There are quite a big difference between an interface and an abstract class, even though both look similar.
    • Interface definition begins with a keyword interface so it is of type interface
    • Abstract classes are declared with the abstract keyword so it is of type class
    • Interface has no implementation, but they have to be implemented.
    • Abstract class’s methods can have implementations and they have to be extended.
    • Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static)
    • Abstract class’s methods can’t have implementation only when declared abstract.
    • Interface can inherit more than one interfaces
    • Abstract class can implement more than one interfaces, but can inherit only one class
    • Abstract class must override all abstract method and may override virtual methods
    • Interface can be used when the implementation is changing
    • Abstract class can be used to provide some default behavior for a base class.
    • Interface makes implementation interchangeable
    • Interface increase security by hiding the implementation
    • Abstract class can be used when implementing framework
    • Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework.
However, in practice when you come across with some application-specific functionality that only your application can perform, such as startup and shutdown tasks etc. The abstract base class can declare virtual shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, it can execute the method defined by the child class. 

What is Implicit and Explicit Interface Implementations?

As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same.
Let's consider the interfaces defined below.
interface IDisposable
{
    void Dispose();
}  
Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose.
class Student : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Student.Dispose");
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("IDisposable.Dispose");
    }
}  


What is 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”.

What is a delegate?

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

  1. The name of the method on which it make calls.
  2. Any argument (if any) of this method.
  3. The return value (if any) of this method

Where are Delegates used?

The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a mouse click) takes place. 

This method needs to be invoked by the runtime when the event occurs. Hence this method, that you defined, is passed as a parameter to a delegate.


Defining a Delegate in C#
when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

public delegate int DelegateName(int x, int y);

A Delegate Usage Example

namespace MyFirstDelegate
{
    //This delegate can point to any method,
    //taking two integers and returning an
    //integer.
    public delegate int MyDelegate(int x, int y);
    //This class contains methods that MyDelegate will point to.
    public class MyClass
    {
        public static int Add(int x, int y)
        {
            return x + y;
        }
        public static int Multiply(int x, int y)
        {
            return x * y;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Create an Instance of MyDelegate
            //that points to MyClass.Add().
            MyDelegate del1 = new MyDelegate(MyClass.Add);
            //Invoke Add() method using the delegate.
            int addResult = del1(5, 5);
            Console.WriteLine("5 + 5 = {0}\n", addResult);
            //Create an Instance of MyDelegate
            //that points to MyClass.Multiply().
            MyDelegate del2 = new MyDelegate(MyClass.Multiply);
            //Invoke Multiply() method using the delegate.
            int multiplyResult = del2(5, 5);
            Console.WriteLine("5 X 5 = {0}", multiplyResult);
            Console.ReadLine();
        }
    }}
Delegate ability to Multicast

Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= .

Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list.

A Multicast Delegate Example
namespace MyMulticastDelegate
{
    //this delegate will be used to call more than one
    //method at once
    public delegate void MulticastDelegate(int x, int y);
    //This class contains methods that MyDelegate will point to.
    public class MyClass
    {
        public static void Add(int x, int y)
        {
            Console.WriteLine("You are in Add() Method");
            Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);
        }
        public static void Multiply(int x, int y)
        {
            Console.WriteLine("You are in Multiply() Method");
            Console.WriteLine("{0} X {1} = {2}", x, y, x * y);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Create an Instance of MulticastDelegate
            //that points to MyClass.Add().
            MulticastDelegate del = new MulticastDelegate(MyClass.Add);
            //using the same instance of MulticastDelegate
            //to call MyClass.Multibly() by adding it to it's
            //invocation list.
            del += new MulticastDelegate(MyClass.Multiply);
            //Invoke Add() and  Multiply() methods using the delegate.
            //Note that these methods must have a void return vlue
            Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");
            del(5, 5);

            //removing the Add() method from the invocation list
            del -= new MulticastDelegate(MyClass.Add);
            Console.WriteLine("\n\n****Add() Method removed.****\n\n");
            //this will invoke the Multibly() method only.
            del(5, 5);
        }
    }
}


What is a events? 

Events are members of the class that raises them. When some thing happens a class can raise an event, which have a message that contain informations about the event (event arguments) and send them out to the rest of the application, other parts of the application can respond to the event by excuting methods called event handlers.

Event handler is a method that has the same signature as the event and this method is executed when the event occurs.
To define an event you need first to define a delegate that contains the methods that will be called when the event raised, and then you define the event based on that delegate.

Example:

public
class MyClass{    public delegate void MyDelegate(string message);    public event MyDelegate MyEvent;}
Raising an events is a simple step. First you check the event agaist a null value to ensure that the caller has registered with the event, and then you fire the event by specifying the event by name as well as any required parameters as defined by the associated delegate.

Example
if (MyEvent != null)    MyEvent(message);

So far so good, in the previous section you saw how to define an event and the delegate associated with it and how to raise this event.

Now you will see how the other parts of the application can respond to the event. To do this you just need to register the event handlers.

when you want to register an event handler with an event you must follow this pattern:

MyClass myClass1 = new MyClass();
MyClass.MyDelegate del = new MyClass.MyDelegate(myClass1_MyEvent);myClass1.MyEvent += del;
or you can do this in one line of code

myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

//this is the event handler
//this method will be executed when the event raised.
static void myClass1_MyEvent(string message)
{
    //do something to respond to the event.}

Let's see a full example to demonstrate the concept:
namespace EventsInCSharp
{
    public class MyClass
    {
        public delegate void MyDelegate(string message);
        public event MyDelegate MyEvent;

        //this method will be used to raise the event.
        public void RaiseEvent(string message)
        {
            if (MyEvent != null)
                MyEvent(message);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

            Console.WriteLine("Please enter a message\n");
            string msg = Console.ReadLine();

            //here is we raise the event.
            myClass1.RaiseEvent(msg);
            Console.Read();
        }
        //this method will be executed when the event raised.
        static void myClass1_MyEvent(string message)
        {
            Console.WriteLine("Your Message is: {0}", message);
        }
    }
}
we are doing great, but what if you want to define your event and it's associated delegate to mirrors Microsoft's recommended event pattern. To do so you must follow this patten:
public delegate void MyDelegate(object sender, MyEventArgs e);
public event MyDelegate MyEvent;
As you can see the first parameter of the delegate is a System.Object, while the second parameter is a type deriving from System.EventArgs.

The System.Object parameter represents  a reference  to the object that sent the event(such as MyClass), while the second parameter represents information regarding the event.

If you define a simple event that is not sending any custom information, you can pass an instance of EventArgs directly.
let's see an example:

namespace
MicrosoftEventPattern
{
    public class MyClass
    {
        public delegate void MyDelegate(object sender, MyEventArgs e);
        public event MyDelegate MyEvent;

        public class MyEventArgs : EventArgs
        {
            public readonly string message;
            public MyEventArgs(string message)
            {
                this.message = message;
            }
        }
        //this method will be used to raise the event.
        public void RaiseEvent(string msg)
        {
            if (MyEvent != null)
                MyEvent(this, new MyClass.MyEventArgs(msg));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

            Console.WriteLine("Please enter a message\n");
            string msg = Console.ReadLine();

            //here is we raise the event.
            myClass1.RaiseEvent(msg);
            Console.Read();
        }
        static void myClass1_MyEvent(object sender, MyClass.MyEventArgs e)
        {
            if (sender is MyClass)
            {
                MyClass myClass = (MyClass)sender;
                Console.WriteLine("Your Message is: {0}", e.message);
            }
        }
    }
}

 

What is Encapsulation (or information hiding)?

The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.
class.gif
In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.
There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
IStudent myStudent = new LocalStudent();
IStudent myStudent = new ForeignStudent();
According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize implementing information through the IStudent interface.


What is Polymorphism?

Polymorphism means same operation may behave differently on different classes.
Eg:
Method Overloading is an example of Compile Time Polymorphism.
Method Overriding is an example of Run Time Polymorphism
Does C#.net supports multiple inheritance?
No. A class can inherit from only one base class, however a class can implements many interface, which servers some of the same purpose without increasing complexity.
How many types of Access Modifiers.
1) Public – Allows the members to be globally accessible.
2) Private – Limits the member’s access to only the containing type.
3) Protected – Limits the member’s access to the containing type and all classes derived from the containing type.
4) Internal – Limits the member’s access to within the current project.

Method Overloading

Method with same name but with different arguments is called method overloading.
Method Overloading forms compile-time polymorphism.
Eg:
class A1
{
void hello()
{ Console.WriteLine(“Hello”); }
void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }
}

Method Overriding

Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
Method overriding forms Run-time polymorphism.
Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
Eg1:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.

Virtual Method

By declaring base class function as virtual, we allow the function to be overridden in any of derived class.
Eg:
Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}
Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}
static void main()
{
parent objParent = new child();
objParent.hello();
}
//Output
Hello from Child.


Boxing and Un-Boxing

Boxing: means converting value-type to reference-type.
Eg:
int I = 20;
string s = I.ToSting();
UnBoxing: means converting reference-type to value-type.
Eg:
int I = 20;
string s = I.ToString(); //Box the int
int J = Convert.ToInt32(s); //UnBox it back to an int.
Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in the heap.

Value Type and Reference Type
A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.

Value Type

As name suggest Value Type stores “value” directly.
For eg:
//I and J are both of type int
I = 20;
J = I;
int is a value type, which means that the above statements will results in two locations in memory.
For each instance of value type separate memory is allocated.
Stored in a Stack.
It Provides Quick Access, because of value located on stack.

Reference Type

As name suggest Reference Type stores “reference” to the value.
For eg:
Vector X, Y; //Object is defined. (No memory is allocated.)
X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.)
X.value = 30; //Initialising value field in a vector class.
Y = X; //Both X and Y points to same memory location. //No memory is created for Y.
Console.writeline(Y.value); //displays 30, as both points to same memory
Y.value = 50;
Console.writeline(X.value); //displays 50.
Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;
Reference type are stored on Heap.
It provides comparatively slower access, as value located on heap.
ref keyword
Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable “must” be initialized before it is passed into a method.
out keyword
out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.
Note: You must assigned value to out parameter in method body, otherwise the method won’t compiled.

this Keyword
Each object has a reference “this” which points to itself.
Two uses of this keyword.
o Can be used to refer to the current object.
o It can also be used by one constructor to explicitly invoke another constructor of the same class.
Eg1:
class Student
{
private string name;
private int age;
Student(string name, int age)
{
this.name = name;
this.age = age;
}
}
Eg2:
class Circle
{
double x,y,radius;
Circle(double x){
this(x,0,1);
}
Circle(double x, double y){
this(x,y,1);
}
Circle(double x, double y, double radius){
this.x = x;
this.y = y;
this.radius = radius;
}
}

Constructor

  • A constructor is a special method whose task is to initialize the object of its class.
  • It is special because its name is the same as the class name.
  • They do not have return types, not even void and therefore they cannot return values.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • Constructor is invoked whenever an object of its associated class is created.
  • Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().

Static Members of the class

Static members belong to the whole class rather than to individual object

Static members are accessed with the name of class rather than reference to objects.
Eg:
class Test
{
public int rollNo;
public int mathsMarks;
public static int totalMathMarks;
}
class TestDemo
{
public static void main()
{
Test stud1 = new Test();
stud1.rollNo = 1;
stud1.mathsMarks = 40;
stud2.rollNo = 2;
stud2.mathsMarks = 43;
Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;
}
}

Static Method of the class

Methods that you can call directly without first creating an instance of a class. Eg: Main() Method, Console.WriteLine()
You can use static fields, methods, properties and even constructors which will be called before any instance of the class is created.
As static methods may be called without any reference to object, you can not use instance members inside static methods or properties, while you may call a static member from a non-static context. The reason for being able to call static members from non-static context is that static members belong to the class and are present irrespective of the existence of even a single object.

Static Constructor

In C# it is possible to write a static no-parameter constructor for a class. Such a class is executed once, when first object of class is created.
One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used.
Eg:
Class MyClass
{
static MyClass()
{
//Initialization Code for static fields and properties.
}
}
Finalize() Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize(). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.
For example
Protected override void Finalize()
{
try
{
Console.WriteLine(“Destructing Object….”);
//put some code here.
}
finally
{
base.Finalize();
}
}

Destructor

A destructor is just opposite to constructor.
It has same as the class name, but with prefix ~ (tilde).
They do not have return types, not even void and therefore they cannot return values.
destructor is invoked whenever an object is about to be garbage collected
Eg:
class person
{
//constructor
person()
{
}
//destructor
~person()
{
//put resource freeing code here.
}
}
What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called?
Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.


References:

1 comment: