oops concepts

127
OOPS concept from C# Corner OOPS Concepts and .NET Part 1: Classes, Objects, and Structures Summary The following article kicks off a three-part article series that will present definitions and samples for different Object-Oriented Programming concepts and its implementation in .NET. The first part will examine the concepts of classes, objects, and structures. The second part will examine the concepts of inheritance, abstraction, and polymorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading. Introduction Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object's data, functions, and its relationship with other objects. Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET. Class The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example is house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups of objects that will always have the same features. Class members A class has different members, and developers in Microsoft suggest programming them in the following order: Page 1

Upload: sunil-kumar-sharma

Post on 19-Nov-2014

41 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: OOPS Concepts

OOPS concept from C# Corner

OOPS Concepts and .NET Part 1: Classes, Objects, and Structures

Summary

The following article kicks off a three-part article series that will present definitions and samples for different Object-Oriented Programming concepts and its implementation in .NET. The first part will examine the concepts of classes, objects, and structures. The second part will examine the concepts of inheritance, abstraction, and polymorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Introduction

Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object's data, functions, and its relationship with other objects.

Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET.

Class

The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template. Another great example is house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups of objects that will always have the same features.

Class members

A class has different members, and developers in Microsoft suggest programming 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 reallocating 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.

Page 1

Page 2: OOPS Concepts

OOPS concept from C# Corner

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.

The following sample code illustrates a sample class in C#:

/// C# ///Imported namespacesusing System;/// Namespace: Consider using CompanyName.Product.ComponentTypenamespace DotNetTreats.OOSE.OOP_CSharp {///Class declarationpublic class employee {///Fieldsprivate string _name;private int _salary;///Constantsprivate const int anualBonus = 1000;///Constructorpublic employee(){}///Propertiespublic string Name {get {return _name;}set {_name = value;}}public int Salary {get {return _salary;}set

Page 2

Page 3: OOPS Concepts

OOPS concept from C# Corner

{_salary = value;}}/// Event handlerspublic event EventHandler OnPromotion {add {}remove {}}/// Methodspublic void DuplicateSalary() {_salary = _salary*2;}}}

Listing 1. Sample class implementation in C#

The following sample code illustrates a sample class in VB.NET:

' VB.NET 'Imported namespacesImports System' Namespace: Consider using CompanyName.Product.ComponentTypeNamespace DotNetTreats.OOSE.OOP_VBNET'Class declarationPublic Class employee'FieldsPrivate _name As StringPrivate _salary As Integer'ConstantsPrivate Const anualBonus As Integer = 1000'Constructors Public Sub New()MyBase.New()End Sub'PropertiesPublic Property Name() As StringGetReturn _nameEnd GetSet(ByVal Value As String)_name = valueEnd SetEnd PropertyPublic Property Salary() As Integer

Page 3

Page 4: OOPS Concepts

OOPS concept from C# Corner

GetReturn _salaryEnd GetSet(ByVal Value As Integer)_salary = valueEnd SetEnd Property' Event handlersPublic Event OnPromotion As EventHandler'MethodsPublic Sub DuplicateSalary()_salary = (_salary * 2)End SubEnd ClassEnd Namespace

Listing 2. Sample class implementation in VB.NET

Object

Objects are the building blocks of OOP and are commonly defined as variables or data structures that encapsulate behavior and data in a programmed unit. Objects are items that can be individually created, manipulated, and represent real world things in an abstract way.

Object composition

Every object is composed by:

Object identity: Means that every object is unique and can be differentiated from other objects. Each time and object is created (instantiated) the object identity is defined.

Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.

Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.

Structures

Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

The following code sample represents structures in C#:

/// C#struct Point {private int _x;private int _y;Point(int x, int y)

Page 4

Page 5: OOPS Concepts

OOPS concept from C# Corner

{this._x = x;this._y = y; }public int X {get {return _x;}set {_x = value;}}public int Y {get {return _y;}set {_y = value;}}}

Listing 3. Sample structure implementation in C#

The following code sample represents a structure in VB.NET:

' VB.NET

Structure PointPrivate _x As IntegerPrivate _y As IntegerSub New(ByVal x As Integer, ByVal y As Integer)MyBase.New()Me._x = xMe._y = yEnd SubPublic Property X() As IntegerGetReturn _xEnd GetSet(ByVal Value As Integer)_x = valueEnd SetEnd PropertyPublic Property Y() As IntegerGet

Page 5

Page 6: OOPS Concepts

OOPS concept from C# Corner

Return _yEnd GetSet(ByVal Value As Integer)_y = valueEnd SetEnd PropertyEnd Structure

Listing 4. Sample structure implementation in VB.NET

Conclusion

OOP is full of abstract concepts, and the best approach to understand them is practical and not only theoretical. I learned more OOP after making some designs and after implementing some components. The concepts presented in this article might clarify the meaning, but I strongly recommend to go and have fun playing around with OOP. In this article, I examined the concept of classes, objects, and structs. The second part will examine the concepts of inheritance, abstraction, and polymorphism.

Page 6

Page 7: OOPS Concepts

OOPS concept from C# Corner

OOPS Concepts and .NET Part 2: Inheritance, Abstraction, & Polymorphism

Summary

The following article is the second of a three-part article series that presents definitions and samples for different Object-Oriented Programming (OOP) concepts and its implementation in .NET. The first part examined the concepts of classes, objects, and structures. This part examines the concepts of inheritance, abstraction, and polymorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Introduction

In Part 1 of Object-Oriented Programming Concepts and .NET, I defined the concepts of class, object, and structure. In addition to defining the concepts, I explained real world samples and presented sample code in C# and VB.NET to create classes and structs. The first article also explains objects as independent building blocks.

In Part 2 of Object-Oriented Programming Concepts and .NET, I will explain the concepts of inheritance, abstraction, and polymorphism. I will also present a Unified Model Language (UML) class diagram to represent an object model that will help as a visual aid to explain some concepts. The purpose of this article is to explain a series of relationships between objects.

Inheritance

In the real world there are many objects that can be specialized. In OOP, a parent class can inherit its behavior and state to children classes. This concept was developed to manage generalization and specialization in OOP and is represented by a is-a relationship.

The following OO terms are commonly used names given to parent and child classes in OOP:

Superclass: Parent class. Subclass: Child class. Base class: Parent class. Derived class: Child class

The most common real world sample to explain inheritance is the geometric shapes object model. Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are geometric shapes. The following figure shows a sample set of geometric figures:

Page 7

Page 8: OOPS Concepts

OOPS concept from C# Corner

Figure 1. Geometric shapes.

The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. In Figure 1, each shape has its own color. Each shape has also particular formulas to calculate its area and perimeter.

Inheritance makes code elegant and less repetitive. If we know that all shapes have color, should we program a color attribute for each shape? The answer is no! Would it be a better idea to create a shape class that has a color attribute and to make all the specialized shapes to inherit the color attribute? The answer is yes!

An object model for this sample could have a shape parent class and a derived class for each specific shape. The following UML class diagram shows the set of classes needed to model the geometric shapes sample. Observe the field, properties, and methods for each class:

Page 8

Page 9: OOPS Concepts

OOPS concept from C# Corner

Figure 2. The Shape class is the parent class. Square, Rectangle, and Circle are derived classes that inherit from Shape. The triangle-connector in the diagram represents an is-a relationship.

The .NET framework has many base classes. Everything is derived from System.Object. You can create almost anything you imagine using the built-in functionality provided in the .NET Framework Class Library.

To create a derived class in C#, the class declaration should be done as:

class child: parent

To create a derived class in VB.NET, the class declaration should be done as:

Class childInherits parentEnd Class

Page 9

Page 10: OOPS Concepts

OOPS concept from C# Corner

Multiple inheritance

Multiple inheritance is the possibility that a child class can have multiple parents. Human beings have always two parents, so a child will have characteristics from both parents.

In OOP, multiple inheritance might become difficult to handle because it allows ambiguity for the compiler. There are programming languages such as C++ that allow multiple inheritance; however, other programming languages such as Java and the .NET Framework languages do not allow multiple inheritance. Multiple inheritance can be emulated in .NET using Multiple Interface Inheritance, which I will explain in Part 3 of this series.

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

To create a sealed class in VB.NET, the class declaration should be done as:

NonInheritable Class Shape

Abstraction

Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).

An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.

Figure 2 shows a Shape class, which is an abstract class. In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. The parent class shape forces all derived classes to define the behavior for CalculateArea() and CalculatePerimeter(). Another great example is a bank account. People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account.

To create an abstract class in C#, the class declaration should be done as:

abstract class Shape

To create an abstract class in VB.NET, the class declaration should be done as:

MustInherit Class Shape

To following code shows a sample implementation of an abstract class:

Page 10

Page 11: OOPS Concepts

OOPS concept from C# Corner

/// C#using System;namespace DotNetTreats.OOSE.OOPSamples{public abstract class Shape{private float _area;private System.Drawing.Color _color;private float _perimeter;public float Area{get{return _area;}set{_area = value;}}public System.Drawing.Color Color{get{return _color;}set{_color = value;}}public float Perimeter{get{return _perimeter;}set{_perimeter = value;}}public abstract void CalculateArea();public abstract void CalculatePerimeter();}}

Listing 1. The Shape abstract class in C#.

Page 11

Page 12: OOPS Concepts

OOPS concept from C# Corner

Polymorphism

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

Figure 2 shows a Rectangle, a Circle, and Square. All of them are shapes and as shapes their area and perimeter can be calculated; however, each shape calculates its area in a specialized way. Declaring a member as abstract allows polymorphism. The Shape class defines the CalculateArea() and CalculatePerimeter() methods as abstract, this allows each derived class to override the implementation of the parent's methods.

To following sample code shows an implementation of a derived class (rectangle). The specific CalculateArea() and CalculatePerimeter() methods for the rectangle class illustrate polymorphism:

/// C# using System;namespace DotNetTreats.OOSE.OOPSamples{class Rectangle : Shape{private float _height;private float _width;public rectangle(float height, float width){_height = height;_width = width;}public float Height{get{return _height;}set{_height = value;}}public float Width{get{return _width;}set{_width = value;}}public override void CalculateArea(){

Page 12

Page 13: OOPS Concepts

OOPS concept from C# Corner

this.Area = _height * _width; }public override void CalculatePerimeter(){this.Perimeter = (_height * 2) + (_width * 2);}}}

Listing 2. Polymorphism represented in the Rectangle's methods.

Virtual keyword

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

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

public virtual void Draw()

To create a virtual member in VB.NET, use the Overridable keyword:

Public Overridable Function Draw()

Override keyword

Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

To override a member in C#, use the override keyword:

public override void CalculateArea()

To override a member in VB.NET, use the Overrides keyword:

Public Overrides Function CalculateArea()

Conclusion

Inheritance allows developers to manage a generalization and specialization relationship between objects. OOP concepts such as abstraction and polymorphism help to define better object models where object hierarchies are designed with reusability in mind. In this article, I examined the concept of inheritance, abstraction, and polymorphism. The third and last part of this series will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Page 13

Page 14: OOPS Concepts

OOPS concept from C# Corner

Abstract Class Vs Interface

Years ago when I was interviewed, I had been asked to explain the differences and main motto behind Abstract class and Interfaces. Interviewers seemed unsatisfied by the answers I gave, it seemed like they wanted to hear some specific points. I also had many doubts and I failed to express the concepts programmatically in what scenario I would choose to use these. I Googled and got disappointed. Much of R&D and also the fruit of experience made me understand these concepts. After years, I am still unable to find an article that explains when to use Abstract class and when to use Interfaces with a good example.

This is the reason I thought of writing this article hoping to share the most basic concepts of Object Oriented Programming. For a mature programmer, it is important to give a logical explanation and I suggest the candidates be prepared with some real world example (a bit of pseudo code) to present in an interview. The code comes handy when you fall short of words.

I am assuming you have all the basic knowledge of how to code Abstract class and Interfaces. I will skip the coding part as I think MSDN has given its best. There are thousands of articles on the web which explain how to code, advantages and language differences. I am focusing on when to use Abstract class and when to use Interfaces.

For more details on these concepts, please go through the references at the end of this article.

Contents

1. Brief Introduction2. Motto behind Abstract class and Interface3. Few advantages4. When to use Abstract class and when to use Interface5. Conclusion6. References

Brief Introduction

Abstract Class

These classes are either partially implemented, or not at all implemented.

This class can contain declarations and also implementations. We cannot make instance of Abstract class. We must inherit to use this class. A non-abstract class derived from an Abstract class must include implementations for all inherited

abstract methods. Abstract class can contain abstract methods, abstract property as well as other members (just like normal

class).

Page 14

Page 15: OOPS Concepts

OOPS concept from C# Corner

Interface

Interface is a pure abstract entity:

It contains only the declaration. We cannot make instance of an Interface. We must inherit to use Interface. A class which implements the interface should implement all the members of an Interface. Members of an Interface are always public.

Few Advantages

An advantage of Abstract class over Interface

If you want to have additional functionalities for the interface, you must implement the new ones in all of the classes that implement the changed interface. The code will not work until you make the change. But if you want to have additional functions to the Abstract class, you can have default implementation. Your code still might work without many changes.

An advantage of Interface over Abstract class

A class can inherit multiple interfaces but can inherit only one class.

Now let us discuss the most important part - when to use Abstract and when to use Interface.

When to Use Abstract and When to Use Interface

Let me explain it with reference to the scenario.

Let us take a classification called Human. As it is a very general classification, I can put all the Human related common data in Abstract class. These common data could be First Name, Last Name, Gender, Education, Occupation, Residence, etc. with some functions as virtual (or overridable), e.g., an occupation which differs from human to human.

Aim of Interface: We want the implementing object to acquire this ability.Aim of Abstraction: We want the derived object to belong to some group. Abstraction gives the Identity to the derived object.

The sentence "Object A is a Human" is more meaningful than the sentence "Object A is an object which has the ability to walk." (Human can walk, an animal, a bird, a machine - consider it is a robot ... that can also walk.)

Why I chose interfaces IEat, IWalk, IDance and ISing

I may want Object A to walk in the morning, to eat in the afternoon or to dance in the evening, or I may not be aware at a particular time what these objects should be doing. The capability of Object A at a particular time is unknown to me. Also every derived object may need not posses the quality of walking, or dancing, or singing. An

Page 15

Page 16: OOPS Concepts

OOPS concept from C# Corner

infant cannot walk, as you know everybody cannot dance and sing. So I created these interfaces so that I can define the combination of these capabilities for different objects explicitly.

Refer to the image below for a more clearer view.

Page 16

Page 17: OOPS Concepts

OOPS concept from C# Corner

Take an example of .NET interfaces IDisposable or IComparable. We implement these interfaces only if necessary. We implement IDisposable mostly when we want to handle COM components and IComparable to compare and sort the objects in an Array.

If you want your class to have an Identity of Form, you must inherit Form class and you can add the ability to dispose, by implementing IDisposable, only if you want to dispose it manually.

Polymorphic Behavior

As I told you, interface adds to the capability of an Object, this means I can have an Object which eats while walking, and the same Object which can dance, and also sing well. This gives polymorphic behavior (single object – multiple capabilities) to the object.

Let me explain this with the help of code.

Collapsenamespace TestAbstractVsInterface{ //Abstract class

abstract class AbstractHuman { public abstract string name { get; set;} public abstract string qualification { get; set;} //Remaining code goes here //. //. //. //. }

//Interfaces

interface IEat { void eat(); }

interface ISing { void sing(); }

interface IWalk { void walk(); }

Page 17

Page 18: OOPS Concepts

OOPS concept from C# Corner

interface IDance { void dance(); }

//Class which inherits abstract class and implements interfaces

class MyClass : AbstractHuman, IEat, ISing, IWalk, IDance { private string strName = "Arati Kadi"; private string strQualification = ""; public override string name { get { return strName; } set { name = value; } }

public override string qualification { get { return strQualification; } set { name = value; } }

public void eat() { //Related code }

public void sing() { //Related code }

public void walk() { //Related code }

public void dance() { //Related code }

//The code snippet below checks by what type class could be //accessed as.

public void getAbilities() { if (this is IEat) Console.WriteLine("MyClass can eat"); if (this is IWalk) Console.WriteLine("MyClass can walk");

Page 18

Page 19: OOPS Concepts

OOPS concept from C# Corner

if (this is ISing) Console.WriteLine("MyClass can sing"); if (this is IDance) Console.WriteLine("MyClass can dance"); } }

//Test Myclass

class testClass { MyClass objMyClass = new MyClass();

public void test() { objMyClass.getAbilities(); } }

}

Output Collapse

MyClass can eat MyClass can walk MyClass can singMyClass can dance

Technically speaking, here the class is used as more than one type. It is used as four Interface Types. It can also be used as its own type and also the type of its base class.

Reusability

Let us consider the same abstract Human class which has the virtual function Eat instead of an Interface IEat.

Now I want to create a class called Bird. As a Bird can also eat, I want to reuse the function which is already there in Human class. Suppose, just because abstract Human class has the function to eat, I cannot derive a Bird class from that. I will tend to change the Bird's identity by doing so, or I may load unnecessary properties to the Bird that could be an education, or employment, or may be the last name. Even worse I may need to change the abstractHuman class so as to include the common behaviors of Bird category. This is totally senseless and messes up the class and objects. Instead, I can have another Abstract class for Birds and choose to have an interface called IEat, which could be implemented by an object of Human and also an object ofBird.

Page 19

Page 20: OOPS Concepts

OOPS concept from C# Corner

Again I want to mention .NET interfaces IDisposable, IComparable (and many). These are available in System namespace and you are reusing to implement with required classes.

Conclusion

Abstract class gives an Identity to the derived object. Interface extends the ability of an object. Interfaces give polymorphic behavior. Abstract class also gives polymorphic behavior. But it is more meaningful to say that Abstract class

simplifies versioning, as the base class is flexible and inheriting class can create many versions of it by additional functions and also by implementing Interfaces.

Interfaces and Abstract Classes both promote reusability.

Page 20

Page 21: OOPS Concepts

OOPS concept from C# Corner

Abstract Class vs Interface

Probably "Difference Between abstract Class and Interface" is the most frequent question being asked in .Net world . In this tutorial, I will explain the difference theoretically followed by code snippet. Theoretically there are basically 5 differences between Abstract Class and Interface which are listed as below :-

1. A class can implement any number of interfaces but a subclass can at most use only one abstract class.2. An abstract class can have non-abstract Methods(concrete methods) while in case of Interface all the

methods has to be abstract.3. An abstract class can declare or use any variables while an interface is not allowed to do so.

So following Code will not compile :-

interface TestInterface{ int x = 4; // Filed Declaration in Interface void getMethod(); string getName();} abstract class TestAbstractClass{ int i = 4; int k = 3; public abstract void getClassName();}

It will generate a compile time error as :-

Error 1 Interfaces cannot contain fields .

So we need to omit Field Declaration in order to compile the code properly.

interface TestInterface{ void getMethod(); string getName();}

abstract class TestAbstractClass{ int i = 4; int k = 3; public abstract void getClassName();}

Above code compiles properly as no field declaration is there in Interface.

4. An abstract class can have constructor declaration while an interface can not do so.

So following code will not compile :-

Page 21

Page 22: OOPS Concepts

OOPS concept from C# Corner

interface TestInterface{ // Constructor Declaration public TestInterface() { } void getMethod(); string getName();} abstract class TestAbstractClass{ public TestAbstractClass() { } int i = 4; int k = 3; public abstract void getClassName();}

Above code will generate a compile time error as :-

Error 1 Interfaces cannot contain constructors

So we need to omit constructor declaration from interface in order to compile our code .

Following code compile s perfectly :-

interface TestInterface{ void getMethod(); string getName();} abstract class TestAbstractClass{ public TestAbstractClass() { } int i = 4; int k = 3; public abstract void getClassName();}

5. An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public.

Note here I am talking about the access specifiers of the member of interface and not about the interface.

Following code will explain it better :-

It is perfectly legal to give provide access specifier as Public (Remember only public is allowed)

Page 22

Page 23: OOPS Concepts

OOPS concept from C# Corner

public interface TestInterface{ void getMethod(); string getName();}

Above code compiles perfectly.

It is not allowed to give any access specifier to the members of the Interface.

interface TestInterface{ public void getMethod(); public string getName();}

Above code will generate a compile time error as :-

Error 1 The modifier 'public' is not valid for this item.

But the best way of declaring Interface will be to avoid access specifier on interface as well as members of interface.

interface Test{ void getMethod(); string getName();}

Page 23

Page 24: OOPS Concepts

OOPS concept from C# Corner

Object Oriented Concepts in C#

Key Concepts of Object Orientation

Encapsulation Polymorphism Inheritance.

Abstraction is the ability to generalize an object as a data type that has a specific set of characteristics and is able to perform a set of actions.

Object-oriented languages provide abstraction via classes. Classes define the properties and methods of an object type.

Examples:

You can create an abstraction of a dog with characteristics, such as color, height, and weight, and actions such as run and bite. The characteristics are called properties, and the actions are called methods.

A Recordset object is an abstract representation of a set of data.

Classes are blueprints for Object.Objects are instance of classes.

C# Example of Class:

public class Draw{// Class code.}

Object References

When we work with an object we are using a reference to that object. On the other hand, when we are working with simple data types such as Integer, we are working with the actual value rather than a reference.

When we create a new object using the New keyword, we store a reference to that object in a variable. For instance:

Draw MyDraw = new Draw;

This code creates a new instance of Draw. We gain access to this new object via the MyDraw variable. This variable holds a reference to the object.

Now we have a second variable, which also has a reference to that same object. We can use either variable interchangeably, since they both reference the exact same object. The thing we need to remember is that the variable we have is not the object itself but, rather, is just a reference or pointer to the object itself.

Early binding means that our code directly interacts with the object, by directly calling its methods. Since the compiler knows the object's data type ahead of time, it can directly compile code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to aid our development efforts; it allows the compiler to ensure that we are referencing methods that do exist and that we are providing the proper parameter values.

Page 24

Page 25: OOPS Concepts

OOPS concept from C# Corner

Late binding means that our code interacts with an object dynamically at run-time. This provides a great deal of flexibility since our code literally doesn't care what type of object it is interacting with as long as the object supports the methods we want to call. Because the type of the object isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is possible but we get unprecedented flexibility in exchange.

If we enable strict type checking by using Option Strict On at the top of our code modules, then the IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and so we have easy access to the use of late binding within our code.

Access Modifiers

Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

Public is visible to everyone. A public member can be accessed using an instance of a class, by a class's internal code, and by any descendants of a class.

Private is hidden and usable only by the class itself. No code using a class instance can access a private member directly and neither can a descendant class.

Protected members are similar to private ones in that they are accessible only by the containing class. However, protected members also may be used by a descendant class. So members that are likely to be needed by a descendant class should be marked protected.

Page 25

Page 26: OOPS Concepts

OOPS concept from C# Corner

Internal/Friend is public to the entire application but private to any outside applications. Internal is useful when you want to allow a class to be used by other applications but reserve special functionality for the application that contains the class. Internal is used by C# and Friend by VB .NET.

Protected Internal may be accessed only by a descendant class that's contained in the same application as its base class. You use protected internal in situations where you want to deny access to parts of a class functionality to any descendant classes found in other applications.

Composition of an OBJECT

We use an interface to get access to an object's data and behavior. The object's data and behaviors are contained within the object, so a client application can treat the object like a black box accessible only through its interface. This is a key object-oriented concept called Encapsulation. The idea is that any programs that make use of this object won't have direct access to the behaviors or data-but rather those programs must make use of our object's interface.

There are three main parts of Object:

Page 26

Page 27: OOPS Concepts

OOPS concept from C# Corner

1. Interface2. Implementation or Behavior3. Member or Instance variables

Interface

The interface is defined as a set of methods (Sub and Function routines), properties (Property routines), events, and fields (variables or attributes) that are declared Public in scope.

Implementation or Behavior

The code inside of a method is called the implementation. Sometimes it is also called behavior since it is this code that actually makes the object do useful work.Client applications can use our object even if we change the implementation-as long as we don't change the interface. As long as our method name and its parameter list and return data type remain unchanged, we can change the implementation all we want.

So Method Signature depends on:

Method name Data types of parameters Either Parameter is passed ByVal or ByRef. Return type of method.

It is important to keep in mind that encapsulation is a syntactic tool-it allows our code to continue to run without change. However, it is not semantic-meaning that, just because our code continues to run, doesn't mean it continues to do what we actually wanted it to do.

Member or Instance Variables

The third key part of an object is its data, or state. Every instance of a class is absolutely identical in terms of its interface and its implementation-the only thing that can vary at all is the data contained within that particular object.

Member variables are those declared so that they are available to all code within our class. Typically member variables are Private in scope-available only to the code in our class itself. They are also sometimes referred to as instance variables or as attributes. The .NET Framework also refers to them as fields. We shouldn't confuse instance variables with properties. A Property is a type of method that is geared around retrieving and setting values, while an instance variable is a variable within the class that may hold the value exposed by a Property.

Interface looks like a class, but has no implementation.

The only thing it contains is definitions of events, indexers, methods and/or properties. The reason interfaces only provide definitions is because they are inherited by classes and structs, which must provide an implementation for each interface member defined. So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

Page 27

Page 28: OOPS Concepts

OOPS concept from C# Corner

Because interfaces must be defined by inheriting classes and structs, they define a contract. For instance, if class foo inherits from the IDisposable interface, it is making a statement that it guarantees it has the Dispose() method, which is the only member of the IDisposable interface. Any code that wishes to use class foo may check to see if class foo inherits IDisposable. When the answer is true, then the code knows that it can call foo.Dispose().

Defining an Interface: MyInterface.c

interface IMyInterface{void MethodToImplement();}

Above listing shows defines an interface named IMyInterface. A common naming convention is to prefix all interface names with a capital "I", but this is not mandatory. This interface has a single method named MethodToImplement(). This could have been any type of method declaration with different parameters and return types. Notice that this method does not have an implementation (instructions between curly braces- {}), but instead ends with a semi-colon, ";". This is because the interface only specifies the signature of methods that an inheriting class or struct must implement.

All the methods of Interface are public by default and no access modifiers (like private, public) are allowed with any method of Interface.

Using an Interface: InterfaceImplementer.cs

class InterfaceImplementer : IMyInterface{public void MethodToImplement(){Console.WriteLine("MethodToImplement() called.");}}

The InterfaceImplementer class in above listing implements the IMyInterface interface. Indicating that a class inherits an interface is the same as inheriting a class. In this case, the following syntax is used:

class InterfaceImplementer : IMyInterface

Note that this class inherits the IMyInterface interface; it must implement its all members. While implementing interface methods all those needs to be declared public only. It does this by implementing the MethodToImplement() method. Notice that this method implementation has the exact same signature, parameters and method name, as defined in the IMyInterface interface. Any difference will cause a compiler error. Interfaces may also inherit other interfaces. Following listing shows how inherited interfaces are implemented.

Interface Inheritance: InterfaceInheritance.cs

using System;interface IParentInterface{void ParentInterfaceMethod();}interface IMyInterface : IParentInterface{

Page 28

Page 29: OOPS Concepts

OOPS concept from C# Corner

void MethodToImplement();}class InterfaceImplementer : IMyInterface{public void MethodToImplement(){Console.WriteLine("MethodToImplement() called.");}public void ParentInterfaceMethod(){Console.WriteLine("ParentInterfaceMethod() called.");}}

The code in above listing contains two interfaces: IMyInterface and the interface it inherits, IParentInterface. When one interface inherits another, any implementing class or struct must implement every interface member in the entire inheritance chain. Since the InterfaceImplementer class in above listing inherits from IMyInterface, it also inherits IParentInterface. Therefore, the InterfaceImplementer class must implement the MethodToImplement() method specified in the IMyInterface interface and the ParentInterfaceMethod() method specified in the IParentInterface interface.

In summary, you can implement an interface and use it in a class. Interfaces may also be inherited by other interface. Any class or struct that inherits an interface must also implement all members in the entire interface inheritance chain.

Inheritance is the idea that one class, called a subclass, can be based on another class, called a base class. Inheritance provides a mechanism for creating hierarchies of objects.

Inheritance is the ability to apply another class's interface and code to your own class.

Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit base class members marked with protected or greater access. The derived class is specialized to provide more functionality, in addition to what its base class provides. Inheriting base class members in derived class is not mandatory.

Access Keywords

base -> Access the members of the base class.this -> Refer to the current object for which a method is called.

The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class. A base class access is permitted only in a constructor, an instance method, or an instance property accessor.

In following example, both the base class, Person, and the derived class, Employee, have a method named Getinfo. By using the base keyword, it is possible to call the Getinfo method on the base class, from within the derived class.

// Accessing base class members

using System;public class Person

Page 29

Page 30: OOPS Concepts

OOPS concept from C# Corner

{protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public virtual void GetInfo(){Console.WriteLine("Name: {0}", name);Console.WriteLine("SSN: {0}", ssn);}}class Employee: Person{public string id = "ABC567EFG";public override void GetInfo(){// Calling the base class GetInfo method:base.GetInfo();Console.WriteLine("Employee ID: {0}", id);}}class TestClass {public static void Main(){Employee E = new Employee();E.GetInfo();}}

OutputName: John L. MalgraineSSN: 444-55-6666Employee ID: ABC567EFG

Base class constructors can be called from derived classes. To call a base class constructor, use the base() constructor reference. This is desirable when it's necessary to initialize a base class appropriately.

Here's an example that shows the derived class constructor with an address parameter:

abstract public class Contact{private string address;public Contact(string b_address){this.address = b_address;}}public class Customer : Contact{public Customer(string c_address) : base(C_address){}}

Page 30

Page 31: OOPS Concepts

OOPS concept from C# Corner

In this code, the Customer class does not have an address, so it passes the parameter to its base class constructor by adding a colon and the base keyword with the parameter to its declaration. This calls the Contact constructor with the address parameter, where the address field in Contact is initialized.

One more example which shows how base-class constructor is called when creating instances of a derived class:

using System;public class MyBase{int num;public MyBase() {Console.WriteLine("In MyBase()");}public MyBase(int i){num = i;Console.WriteLine("in MyBase(int i)");}public int GetNum(){return num;}}public class MyDerived : MyBase{static int i = 32;// This constructor will call MyBase.MyBase()public MyDerived(int ii) : base(){}// This constructor will call MyBase.MyBase(int i)public MyDerived() : base(i){}public static void Main(){MyDerived md = new MyDerived(); // calls public MyDerived() : base(i) and// passes i=32 in base classMyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)}}

Output in MyBase(int i)in MyBase()

The following example will not compile. It illustrates the effects of not including a default constructor in a class definition:

abstract public class Contact

Page 31

Page 32: OOPS Concepts

OOPS concept from C# Corner

{private string address;public Contact(string address){this.address = address;}}public class Customer : Contact{public Customer(string address){}}

In this example, the Customer constructor does not call the base class constructor. This is obviously a bug, since the address field will never be initialized.

When a class has no explicit constructor, the system assigns a default constructor. The default constructor automatically calls a default or parameterless base constructor. Here's an example of automatic default constructor generation that would occur for the preceding example:

public Customer() : Contact(){}

When a class does not declare any constructors, the code in this example is automatically generated. The default base class constructor is called implicitly when no derived class constructors are defined. Once a derived class constructor is defined, whether or not it has parameters, a default constructor will not be automatically defined, as the preceding code showed.

Calling Base Class Members

Derived classes can access the members of their base class if those members have protected or greater access. Simply use the member name in the appropriate context, just as if that member were a part of the derived class itself. Here's an example:

abstract public class Contact{private string address;private string city;private string state;private string zip;public string FullAddress(){string fullAddress = address + '\n' + city + ',' + state + ' ' + zip;return fullAddress;}}public class Customer : Contact{public string GenerateReport(){

Page 32

Page 33: OOPS Concepts

OOPS concept from C# Corner

string fullAddress = FullAddress();// do some other stuff...return fullAddress;}}

In above example, the GenerateReport() method of the Customer class calls the FullAddress() method in its base class, Contact. All classes have full access to their own members without qualification. Qualification refers to using a class name with the dot operator to access a class member-MyObject.SomeMethod(), for instance. This shows that a derived class can access its base class members in the same manner as its own.

More Tips regarding Inheritance:

A static member cannot be marked as override, virtual, or abstract. So following is an error:public static virtual void GetSSN()

You can't call static methods of base class from derived class using base keyword.In above example if you declare a static method as follows:

public class Person{protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public static void GetInfo(){// Implementation}}

now you can't call this method using base.GetInfo() from derived class instead you have to call Person.GetInfo() from derived class.

Inside Static members we can access only static fields, methods etc.Following example will give error, because we can't access name in GetInfo() because name is not static.

public class Person{protected string ssn = "444-55-6666";protected string name = "John L. Malgraine";public static void GetInfo(){Console.WriteLine("Name: {0}", name);Console.WriteLine("SSN: {0}", ssn);}}

Virtual or abstract members cannot be private.

If you are not overriding a virtual method of base class in derived class, you can't use base class method by using base keyword in derived class. Also when you will create an instance of derived class, it will call derived class method and you will only be able to access base class method when you will create instance of base class.

Page 33

Page 34: OOPS Concepts

OOPS concept from C# Corner

You can't decrease access level of a method in derived class when you are overriding a base class method in derived class, vice versa is possible.Means you can make protected method of base class to public in derived class.

The "this" keyword refers to:

the current instance for which a method is called. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors. The following are common uses of this:

To qualify members hidden by similar names, for example:

public Employee(string name, string alias){this.name = name;this.alias = alias;}

In above example, this.name refers to private variable name in the class. If we write name = name, then this will refer to argument name of the constructor Employee and not to private variable name in the class. In this case private variable name will never be initialized.

To pass an object as a parameter to other methods, for example: CalcTax(this);

To declare indexers, for example:

public int this [int param]{get{return array[param];}set{array[param] = value;}}

It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.

In this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. It is also used to pass an object to the method CalcTax, which belongs to another class.

// keywords_this.cs// this exampleusing System;public class Employee{public string name;

Page 34

Page 35: OOPS Concepts

OOPS concept from C# Corner

public string alias;public decimal salary = 3000.00m;// Constructor:public Employee(string name, string alias){// Use this to qualify the fields, name and alias:this.name = name;this.alias = alias;}// Printing method:public void printEmployee(){Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);// Passing the object to the CalcTax method by using this:Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));}}public class Tax{public static decimal CalcTax(Employee E){return (0.08m*(E.salary));}}public class MainClass{public static void Main(){// Create objects:Employee E1 = new Employee ("John M. Trainer", "jtrainer");// Display results:E1.printEmployee();}}

Output Name: John M. TrainerAlias: jtrainerTaxes: $240.00

Abstract Classes

Abstract classes are a special type of base classes. In addition to normal class members, they have abstract class members. These Abstract class members are methods and properties that are declared without an implementation. All classes derived directly from abstract classes must implement all of these abstract methods and properties.

Abstract classes can never be instantiated. This would be illogical, because of the members without implementations.So what good is a class that can't be instantiated? Lots! Abstract classes sit toward the top of a class hierarchy. They establish structure and meaning to code. They make frameworks easier to build. This is possible because abstract classes have information and behavior common to all derived classes in a framework. Take a look at the following example:

Page 35

Page 36: OOPS Concepts

OOPS concept from C# Corner

abstract public class Contact // Abstract Class Contact.{protected string name;public Contact(){// statements...}public abstract void generateReport();abstract public string Name{get;set;}}

Contact, is an abstract class. Contact has two abstract members, and it has an abstract method named generateReport(). This method is declared with the abstract modifier in front of the method declaration. It has no implementation (no braces) and is terminated with a semicolon. The Name property is also declared abstract. The accessors of properties are terminated with semicolons.

public class Customer : Contact // Customer Inherits Abstract Class Contact.{string gender;decimal income;int numberOfVisits;public Customer(){// statements}public override void generateReport(){// unique report}public override string Name{get{numberOfVisits++;return name;}set{name = value;numberOfVisits = 0;}}}public class SiteOwner : Contact{int siteHits;string mySite;public SiteOwner()

Page 36

Page 37: OOPS Concepts

OOPS concept from C# Corner

{// statements}public override void generateReport(){// unique report}public override string Name{get{siteHits++;return name;}set{name = value;siteHits = 0;}}}

The abstract base class Contact has two derived classes, Customer and SiteOwner. Both of these derived classes implement the abstract members of the Contact class. The generateReport() method in each derived class has an override modifier in its declaration. Likewise, the Name declaration contains an override modifier in both Customer and SiteOwner.

C# requires explicit declaration of intent when overriding methods. This feature promotes safe code by avoiding the accidental overriding of base class methods, which is what actually does happen in other languages. Leaving out the override modifier generates an error. Similarly, adding a new modifier also generates an error. Abstract methods must be overridden and cannot be hidden, which the new modifier or the lack of a modifier would be trying to do.

The most famous of all abstract classes is the Object class. It may be referred to as object or Object, but it's still the same class. Object is the base class for all other classes in C#. It's also the default base class when a base class is not specified. The following class declarations produce the same exact results:

abstract public class Contact : Object{// class members}abstract public class Contact{// class members}

Object is implicitly included as a base class if it is not already declared. Besides providing the abstract glue to hold together the C# class framework, object includes built-in functionality, some of which is useful for derived classes to implement.

Difference between Interface and Abstract Class

Page 37

Page 38: OOPS Concepts

OOPS concept from C# Corner

Interfaces are closely related to abstract classes that have all members abstract. For an abstract class, at least one method of the class must be an abstract method that means it may have

concrete methods. For an interface, all the methods must be abstract Class that implements an interface much provide concrete implementation of all the methods definition

in an interface or else must be declare an abstract class In C#, multiple inheritance is possible only through implementation of multiple interfaces. Abstract class

can only be derived once. An interface defines a contract and can only contains four entities viz methods, properties, events and

indexes. An interface thus cannot contain constants, fields, operators, constructors, destructors, static constructors, or types.

Also an interface cannot contain static members of any kind. The modifiers abstract, public, protected, internal, private, virtual, override is disallowed, as they make no sense in this context.

Class members that implement the interface members must be publicly accessible.

Overriding Summery:

A derived class may override a virtual method of the base class with the keyword override. The following restrictions must be followed.

Keyword override is used in the definition of child class method that is going to override the base class's virtual method.

The return type must be the same as the virtual method have in base class. The name of the method should also be same. The parameter-list must also be same in order, number and type of parameters. The accessibility of the overriding method should not be more restricted than that of the accessibility

defined with virtual method of the base class. This accessibility either be the same or less restricted. The virtual methods can be sealed in the child or derived classes to prevent further modifications in the

implementation of the virtual method in the derived classes, by declaring them as sealed methods.

Hiding Base Class Members

Sometimes derived class members have the same name as a corresponding base class member. In this case, the derived member is said to be "hiding" the base class member.

When hiding occurs, the derived member is masking the functionality of the base class member. Users of the derived class won't be able to see the hidden member; they'll see only the derived class member. The following code shows how hiding a base class member works.

abstract public class Contact{private string address;private string city;private string state;private string zip;public string FullAddress(){string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;}}public class SiteOwner : Contact

Page 38

Page 39: OOPS Concepts

OOPS concept from C# Corner

{public string FullAddress(){string fullAddress;// create an address...return fullAddress;}}

In this example, both SiteOwner and its base class, Contact, have a method named FullAddress(). The FullAddress() method in the SiteOwner class hides the FullAddress() method in the Contact class. This means that when an instance of a SiteOwner class is invoked with a call to the FullAddress() method, it is the SiteOwner class FullAddress() method that is called, not the FullAddress() method of the Contact class.

Although a base class member may be hidden, the derived class can still access it. It does this through the base identifier. Sometimes this is desirable. It is often useful to take advantage of the base class functionality and then add to it with the derived class code. The next example shows how to refer to a base class method from the derived class.

abstract public class Contact{private string address;private string city;private string state;private string zip;public string FullAddress(){string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;}}public class SiteOwner : Contact{public string FullAddress(){string fullAddress = base.FullAddress();// do some other stuff...return fullAddress;}}

In this particular example, the FullAddress() method of the Contact class is called from within the FullAddress() method of the SiteOwner class. This is accomplished with a base class reference. This provides another way to reuse code and add on to it with customized behavior.

Versioning

Versioning, in the context of inheritance, is a C# mechanism that allows modification of classes (creating new versions) without accidentally changing the meaning of the code. Hiding a base class member with the methods

Page 39

Page 40: OOPS Concepts

OOPS concept from C# Corner

previously described generates a warning message from the compiler. This is because of the C# versioning policy. It's designed to eliminate a class of problems associated with modifications to base classes.

Here's the scenario: A developer creates a class that inherits from a third-party library. For the purposes of this discussion, we assume that the Contact class represents the third-party library. Here's the example:

public class Contact{// does not include FullAddress() method}public class SiteOwner : Contact{public string FullAddress(){string fullAddress = mySite.ToString();return fullAddress;}}

In this example, the FullAddress() method does not exist in the base class. There is no problem yet. Later on, the creators of the third-party library update their code. Part of this update includes a new member in a base class with the exact same name as the derived class:

public class Contact{private string address;private string city;private string state;private string zip;public string FullAddress(){string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;}}public class SiteOwner : Contact{public string FullAddress(){string fullAddress = mySite.ToString();return fullAddress;}}

In this code, the base class method FullAddress() contains different functionality than the derived class method. In other languages, this scenario would break the code because of implicit polymorphism. However, this does not break any code in C# because when the FullAddress() method is called on SiteOwner, it is still the SiteOwner class method that gets called.

This scenario generates a warning message. One way to eliminate the warning message is to place a new modifier in front of the derived class method name, as the following example shows:

Page 40

Page 41: OOPS Concepts

OOPS concept from C# Corner

using System;public class WebSite{public string SiteName;public string URL;public string Description;public WebSite(){}public WebSite( string strSiteName, string strURL, string strDescription ){SiteName = strSiteName;URL = strURL;Description = strDescription;}public override string ToString(){return SiteName + ", " +URL + ", " +Description;}}public class Contact{public string address;public string city;public string state;public string zip;public string FullAddress(){string fullAddress =address + '\n' +city + ',' + state + ' ' + zip;return fullAddress;}}public class SiteOwner : Contact{int siteHits;string name;WebSite mySite;public SiteOwner(){mySite = new WebSite();siteHits = 0;}public SiteOwner(string aName, WebSite aSite){mySite = new WebSite(aSite.SiteName,aSite.URL,aSite.Description);Name = aName;}new public string FullAddress(){string fullAddress = mySite.ToString();return fullAddress;}public string Name

Page 41

Page 42: OOPS Concepts

OOPS concept from C# Corner

{get{siteHits++;return name;}set{name = value;siteHits = 0;}}}public class Test{public static void Main(){WebSite mySite = new WebSite("Le Financier","http://www.LeFinancier.com","Fancy Financial Site");SiteOwner anOwner = new SiteOwner("John Doe", mySite);string address;anOwner.address = "123 Lane Lane";anOwner.city = "Some Town";anOwner.state = "HI";anOwner.zip = "45678";address = anOwner.FullAddress(); // Different ResultsConsole.WriteLine("Address: \n{0}\n", address);}}

Here's the output:Address:Le Financier, http://www.LeFinancier.com, Fancy Financial Site

This has the effect of explicitly letting the compiler know the developer's intent. Placing the new modifier in front of the derived class member states that the developers know there is a base class method with the same name, and they definitely want to hide that member. This prevents breakage of existing code that depends on the implementation of the derived class member. With C#, the method in the derived class is called when an object of the derived class type is used. Likewise, the method in the base class is called when an object of the Base class type is called. Another problem this presents is that the base class may present some desirable new features that wouldn't be available through the derived class.

To use these new features requires one of a few different workarounds. One option would be to rename the derived class member, which would allow programs to use a base class method through a derived class member. The drawback to this option would be if there were other classes relying upon the implementation of the derived class member with the same name. This scenario will break code and, for this reason, is considered extremely bad form.

Another option is to define a new method in the derived class that called the base class method. This allows users of the derived class to have the new functionality of the base class, yet retain their existing functionality with the derived class. While this would work, there are maintainability concerns for the derived class.

Sealed Classes

Page 42

Page 43: OOPS Concepts

OOPS concept from C# Corner

Sealed classes are classes that can't be derived from. To prevent other classes from inheriting from a class, make it a sealed class. There are a couple good reasons to create sealed classes, including optimization and security.

Sealing a class avoids the system overhead associated with virtual methods. This allows the compiler to perform certain optimizations that are otherwise unavailable with normal classes.

Another good reason to seal a class is for security. Inheritance, by its very nature, dictates a certain amount of protected access to the internals of a potential base class. Sealing a class does away with the possibility of corruption by derived classes. A good example of a sealed class is the String class. The following example shows how to create a sealed class:

public sealed class CustomerStats{string gender;decimal income;int numberOfVisits;public CustomerStats(){}}public class CustomerInfo : CustomerStats // error{}

This example generates a compiler error. Since the CustomerStats class is sealed, it can't be inherited by the CustomerInfo class.The CustomerStats class was meant to be used as an encapsulated object in another class. This is shown by the declaration of a CustomerStats object in the Customer class.

public class Customer{CustomerStats myStats; // okay}

Polymorphism

Polymorphism is reflected in the ability to write one routine that can operate on objects from more than one class-treating different objects from different classes in exactly the same way. For instance, if both Customer and Vendor objects have a Name property, and we can write a routine that calls the Name property regardless of whether we're using a Customer or Vendor object, then we have polymorphism.

A vehicle is a good example of polymorphism. A vehicle interface would only have those properties and methods that all vehicles have, a few of which might include paint color, number of doors, accelerator, and ignition. These properties and methods would apply to all types of vehicles including cars, trucks, and semi-trucks.

Polymorphism will not implement code behind the vehicle's properties and methods. Instead, polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the same vehicle interface, then the client code for all three classes can be exactly the same.

C# gives us polymorphism through inheritance. C# provides a keyword virtual that is used in the definition of a method to support polymorphism.

Page 43

Page 44: OOPS Concepts

OOPS concept from C# Corner

Child class are now free to provide their own implementation of this virtual method, that is called overriding. The following points are important regarding virtual keyword:-

If the method is not virtual, the compiler simply uses the reference type to invoke the appropriate method.

If the method is virtual, the compiler will generate code to checkup the reference type at runtime it is actually denoting to, then the appropriate method is called from the class of the reference type.

When a virtual method is called, runtime check (late method binding) is made to identify the object and appropriate method is invoked, all this is done at runtime.

In case of non-virtual methods, this information is available at compile time, so no runtime check to identify the object is made, so slightly efficient in the way non-virtual methods are called. But the behavior of virtual method is useful in many ways; the functionality they provide is fair enough to bear this slight loss of performance.

Implementing Polymorphism

The key factor here is the ability to dynamically invoke methods in a class based on their type. Essentially, a program would have a group of objects, examine the type of each one, and execute the appropriate method. Here's an example:

using System;public class WebSite{public string SiteName;public string URL;public string Description;public WebSite(){}public WebSite( string strSiteName, string strURL, string strDescription ){SiteName = strSiteName;URL = strURL;Description = strDescription;}public override string ToString(){return SiteName + ", " +URL + ", " +Description;}}

When we inherit above class, we have two choices to invoke constructor of the class. So this is an example of design time polymorphism. Here at design time we have to decide which method we need to invoke while inheriting the class.

Polymorphism is the capability of a program to carry out dynamic operations by implementing methods of multiple derived classes through a common base class reference. Another definition of polymorphism is the ability to treat different objects the same way. This means that the runtime type of an object determines its behavior rather than the compile-time type of its reference.

Page 44

Page 45: OOPS Concepts

OOPS concept from C# Corner

Unified Modeling Language (UML) - Part 1

Introduction

Again I repeat do not think you get an architecture position by reading Interview Questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a short cut.

Happy job hunting......

(B) Define UML?

Unified Modeling Language, a standard language for designing and documenting a system in an object-oriented manner. It has nine diagrams which can be used in design document to express design of software architecture.

(I) Can you explain use case diagrams?

Use case diagram answers what system does from the user point of view. Use case answer "What will the system do?". Use cases are mainly used in requirement document to depict clarity regarding a system. There are three important parts in a use case scenario, actor and use case.

Scenario: A scenario is a sequence of events which happen when a user interacts with the system.

Actor: Actor is the who of the system, in other words the end user.

Use Case: Use case is task or the goal performed by the end user. Below figure "Use Case" shows a simple scenario with "Actor" and a "Use Case". Scenario represents an accountant entering accounts data in the system. As use case's represent action performed they are normally represented by strong verbs.

Actor's are represented by simple stick man and use case by oval shape as shown in figure "Use Case" below.

Figure: Use Case

(I) Can you explain primary and secondary actors?

Actors are further classified in to two types primary and secondary actors. Primary actors are the users who are the active participants and they initiate the user case, while secondary actors are those who only passively participate in the use case.

Page 45

Page 46: OOPS Concepts

OOPS concept from C# Corner

(I) How does a simple use case look like?

Use case's have two views of representation in any requirement document. One is the use case diagrams and the other is a detail step table about how the use case works. So it's like a pair first an over view is shown using a use case diagram and then a table explaining the same in detail. Below is a simple "login" use case shown diagrammatically and then a detail table with steps about how the use case is executed.

Figure: Login Use Case

Use Case Rel001Use Case Name LoginDescription This uses depicts the flow of how user will log-in into the chat application.Primary Actor Simple chat user.Trigger User types chat application on URL of the browser.Pre-condition NA

Assumption No password is currently present for the systemRooms will remain constant as explained in the assumption section of this document

Failed End conditions

Duplicate user name is not allowed in the chat application.

Action User clicks on the log-in button.Main Scenario User types chat application on URL of the browser which in turn opens the main

page. In the main page of application user is popped up with "Enter user name" option

and various "rooms" option drop down menu. User then types the name and selects one of the room from drop down menu and

then clicks on the "Log-in" button. Application then checks whether the user name is unique in the system if not then

user is popped up with error message that user already exist's. After entering the unique name the user is finally logged in the application.

Page 46

Page 47: OOPS Concepts

OOPS concept from C# Corner

Action NAAlternate

ScenarioNA

Success Scenarios

1. Opens page of a selected room in that other user names and their messages can be seen.

Note and Open Issues

NA

Table: Login use case table

Note: You must be wondering why we have this pair why not just a use case table only. Use case diagrams are good to show relationship between use case and they also provide high over view. The table explanation of a use case talks details about the use case. So when a developer or a user is reading a requirement document, he can get an overview by looking at the diagram if he is interested he can read the use case tables for more details.

(I) Can you explain "Extend" and "Include" in use cases?

"Extend" and "Include" define relationships between use cases. Below figure "Extend and Include" shows how these two fundamentals are implemented in a project. The below use case represents a system which is used to maintain customer. When a customer is added successfully it should send an email to the admin saying that a new customer is added. Only admin have rights to modify the customer. First let's define extend and include and then see how the same fits in this use case scenario.

Include: Include relationship represents an invocation of one use case by the other. If you think from the coding perspective its like one function been called by the other function.

Extend: This relationship signifies that the extending use case will work exactly like the base use case only that some new steps will inserted in the extended use case.

Below figure "Extend and Include" shows that "add customer" is same as the "add discounted customer". The "Add discounted customer" has an extra process, to define discount for the discounted customer which is not available for the simple customer. One of the requirements of the project was that when we add a customer, the system should send an email. So after the customer is added either through "Add simple customer" use case or "Add discounted customer" use case it should invoke "send a email" use case. So we have defined the same with a simple dotted line with <<include>> as the relationship.

Page 47

Page 48: OOPS Concepts

OOPS concept from C# Corner

Figure: Extend and Include

Note: One of the points to be noted in the diagram "Extend and Include" is we have defined inheritance relationship between simple and admin user. This also helps us defining a technical road map regarding

relationships between simple and admin user.

(I) Can you explain class diagrams?

Class diagram

Class is basically a prototype which helps us create objects. Class defines the static structure of the project. A class represents family of an object. By using Class we can create uniform objects.

In the below figure you can see how the class diagram looks. Basically there are three important sections which are numbered as shown in the below. Let's try to understand according to the numbering:

Class name: This is the first section or top most section of the Class which represents the name of the Class (clsCustomer).

Attributes: This is the second section or the middle section of the class which represents the properties of the system.

Methods: This section carries operation or method to act on the attributes.

Figure: Three sections of the class

Page 48

Page 49: OOPS Concepts

OOPS concept from C# Corner

Now in the next section we will have a look on Association relationship between these classes.

(B) How do we represent private, public and protected in class diagrams?

In order to represent visibility for properties and methods in class diagram we need to place symbols next to each property and method as shown in figure "Private, Public and Protected". "+" indicates that it's public properties/methods. "-"indicates private properties which means it can not be accessed outside the class. "#" indicate protected/friend properties. Protected properties can only be seen within the component and not outside the component.

Figure: Private, public and protected

(I) what does associations in a class diagram mean?

Associations in Class diagramsA single Class cannot represent the whole module in a project so we need one or more classes to represent a

module. For instance, a module named "customer detail" cannot be completed by the customer class alone , to complete the whole module we need customer class, address class, phone class in short there is relationship between the classes. So by grouping and relating between the classes we create module and these are termed as Association. In order to associate them we need to draw the arrowed lines between the classes as shown in the below figure.

In the figure "Order is paid by payments class", we can see Order class and the Payment class and arrowed line showing relationship that the order class is paid using payment class in other words order class is going to be used by payment class to pay the order. The left to right marked arrow basically shows the flow that order class uses the payment class.

In case payment class using the order class then the marked arrow should be right to left showing the direction of the flow.

Page 49

Page 50: OOPS Concepts

OOPS concept from C# Corner

Figure:- Order is paid by Payments class

There are four signs showing the flow:-

Figure: Direction signs in UML

Multiplicity

Multiplicity can be termed as classes having multiple associations or one class can be linked to instances of many other classes. If you look at the below figure the customer class is basically associated with the address class and also observes the notations (*, 0 and 1).If you look at the right hand side the (1|.*) notation indicates that at least one or many instance of the address class can be present in the customer class. Now towards left hand side we have (0|.*) notation indicating that address class can exist without or many customer class can link him.In order to represent multiplicity of classes we have to show notations like (1|.*), (0|.*) as shown in below figure.

Note: "*" means "many" where as "(0, 1)" means "(zero or at least one)" respectively.

Page 50

Page 51: OOPS Concepts

OOPS concept from C# Corner

Figure: Multiplicity in Classes

(I) Can you explain aggregation and composition in class diagrams?

In this Association there are two types mainly Aggregation Association and Composition Association.

Aggregation Association signifies that the whole object can exist without the Aggregated Object. For example in the below figure we have three classes university class, department class and the Professor Class. The university cannot exist without department which means that university will be closed as the department is closed. In other words lifetime of the university depend on the lifetime of department.

In the same figure we have defined second Association between the department and the Professor. In this case, if the professor leaves the department still the department continues in other words department is not dependent on the professor this is called as Composition Association.

Note: The filled diamond represents the aggregation and the empty diamond represents the composition. You can see the figure below for more details.

Figure: Aggregation and composition in action

(A) What are composite structure diagram and reflexive association in class diagrams?

Composite structure diagram

When we try to show Aggregation and Composition in a complete project the diagram becomes very complicated so in order to keep it simple we can use Composite structure diagram. In the below figure we have shown two

Page 51

Page 52: OOPS Concepts

OOPS concept from C# Corner

diagrams one is normal diagram other is Composite structure diagram and the simplicity can easily be identified. In the composite diagram the aggregated classes are self contained in the main class which makes it simpler to read.

Figure: Composite Structure diagram

Reflexive associations

In many scenarios you need to show that two instances of the same class are associated with each other and this scenario is termed as Reflexive Association. For instance in the below figure shows Reflexive Association in the real project. Here you can see customer class has multiple address class and addresses can be a Head office, corporate office or Regional office. One of the address objects is Head office and we have linked the address object to show Reflexive Association relationship. This is the way we can read the diagram Regional address object is blocked by zero or one instance of Head office object.

Figure: Reflexive association

(I) Can you explain business entity and service class?

Business entity objects represent persistent information like tables of a database. Just making my point clearer they just represent data and do not have business validations as such. For instance below figure "Business entity

Page 52

Page 53: OOPS Concepts

OOPS concept from C# Corner

and service" shows a simple customer table which with three fields "Customer Code"," Customer Address" and "Phone Number". All these fields are properties in "ClsCustomer" class. So "ClsCustomer" class becomes the business entity class. The business entity class by itself can not do anything it"s just a place holder for data. In the same figure we have one more class "ClsServiceCustomer". This class aggregates the business entity class and performs operations like "Add"," Next" (Move to next record), "Prev" (Move to previous record) and "GetItem" (get a customer entity depending on condition).

With this approach we have separated the data from the behavior. The service represents the behavior while the business entity represents the persistent data.

Figure:-Business entity and service

(I) Can you explain System entity and service class?

System entity class represents persistent information which is related to the system. For instance in the below figure "System entity and service class" we have a system entity class which represents information about "loggedindate" and "loggedintime" of the system registry. System service class come in two flavors one is it acts like a wrapper in the system entity class to represent behavior for the persistent system entity data. In the figure you can see how the "ClsAudit" system entity is wrapped by the "ClsAuditSytem" class which is the system service class. "ClsAuditSystem" adds "Audit" and "GetAudit" behavior to the "ClsAudit" system entity class.

Page 53

Page 54: OOPS Concepts

OOPS concept from C# Corner

Figure: System entity and service class

The other flavor of the system service class is to operate on non-persistent information. The first flavor operated on persistent information. For instance the below figure "Non-persistent information" shows how the class "ClsPaymentService" class operates on the payment gateway to Check is the card exists , Is the card valid and how much is the amount in the card ?. All these information are non-persistent. By separating the logic of non-persistent data in to a system service class we bring high reusability in the project.

Figure: Non-persistent information

Note: The above question can be asked in interview from the perspective of how you have separated the behavior from the data. The question will normally come twisted like "How did you separate the behavior from the data?".

(B) Can you explain generalization and specialization?

Generalization and Specialization

In Generalization and Specialization we define the parent-child relationship between the classes. In many instance you will see some of the classes have same properties and operation these classes are called super class and later you can inherit from super class and make sub classes which have their own custom properties. In the below figure there are three classes to show Generalization and Specialization relationship. All phone types have phone number as a generalized property but depending upon landline or mobile you can have wired or simcard connectivity as specialized property. In this diagram the clsphone represent Generalization whereas clslandline and clsmobile represents specialization.

Page 54

Page 55: OOPS Concepts

OOPS concept from C# Corner

Figure: Generalization and Specialization

(B) How do we represent an abstract class and interface UML?

Interface is represented by <<type>> in the class diagram. Below figure "Interface in action" shows we have defined an interface "IContext". Note the "<<type>>" represents an interface. If we want to show that the interface is used in a class we show the same with a line and a simple circle as shown in figure "Interface in Action" below.

Figure: Interface in action

Abstract classes are represented by "{abstract}" as shown in figure "Abstract classes in action".

Page 55

Page 56: OOPS Concepts

OOPS concept from C# Corner

Figure: Abstract classes in action.

(B) How do we achieve generalization and specialization?

By using inheritance.

(I) Can you explain object diagrams in UML?

Class represents shows the static nature of the system. From the previous question you can easily judge that class diagrams shows the types and how they are linked. Classes come to live only when objects are created from them. Object diagram gives a pictorial representation of class diagram at any point of time. Below figure "Object diagram" shows how a class looks in when actual objects are created. We have shown a simple student and course relationship in the object diagram. So a student can take multiple courses. The class diagram shows the same with the multiplicity relationship. We have also shown how the class diagram then looks when the objects are created using the object diagram. We represent object with Object Name: Class Name. For instance in the below figure we have shown "Shiv : ClsStudent" i.e "Shiv" is the object and "ClsStudent" the class. As the objects are created we also need to show data of the properties, the same is represented by "PropertyName=Value" i.e. "StudentName=Shiv".

Figure: Object diagrams

Page 56

Page 57: OOPS Concepts

OOPS concept from C# Corner

The diagram also states that "ClsStudent" can apply for many courses. The same is represented in object diagram by showing two objects one of the "Computer" and the other of "English".

Note: Object diagrams should only be drawn to represent complicated relationship between objects. It's possible that it can also complicate your technical document as lot. So use it sparingly.

(I) Can you explain sequence diagrams?

Sequence diagrams

Sequence diagram shows interaction between objects over a specific period time. Below figure 'Sequence diagram' shows how a sequence diagram looks like. In this sequence diagram we have four objects "Customer","Product","Stock" and "Payment". The message flow is shown vertically in waterfall manner i.e. it starts from the top and flows to the bottom. Dashed lines represent the duration for which the object will be live. Horizontal rectangles on the dashed lines represent activation of the object. Messages sent from a object is represented by dark arrow and dark arrow head. Return message are represented by dotted arrow. So the figure shows the following sequence of interaction between the four objects:

Customer object sends message to the product object to request if the product is available or not. Product object sends message to the stock object to see if the product exists in the stock. Stock object answers saying yes or No. Product object sends the message to the customer object. Customer object then sends a message to the payment object to pay money. Payment object then answers with a receipt to the customer object.

One of the points to be noted is product and stock object is not active when the payment activity occurs.

Figure: Sequence diagram

Page 57

Page 58: OOPS Concepts

OOPS concept from C# Corner

Messages in sequence diagrams

There are five different kinds of messages which can be represented by sequence.

Synchronous and asynchronous messages

Synchronous messages are represented by a dark arrow head while asynchronous messages are shown by a thin arrow head as shown in figure "Synchronous and Asynchronous".

Figure: Synchronous and Asynchronous

Recursive message

We have scenarios where we need to represent function and subroutines which are called recursively. Recursive means the method calling himself. Recursive messages are represented by small rectangle inside a big rectangle with an arrow going from the big rectangle to the small rectangle as shown in figure "Recursive message".

Page 58

Page 59: OOPS Concepts

OOPS concept from C# Corner

Figure: Recursive message

Message iteration

Message iteration represents loops during sequences of activity. Below figure "message iteration" shows how "order" calls the "orderitem" objects in a loop to get cost. To represent loop we need to write "For each <<object name>>". In the below figure the object is the "orderitem". Also note the for each is put in a box to emphasize that it"s a loop.

Page 59

Page 60: OOPS Concepts

OOPS concept from C# Corner

Figure: Message iteration

Message constraint

If we want to represent constraints it is put in a rectangle bracket as shown in figure "message constraint". In the below figure "message constraint" the "customer" object can call "book tickets" only if the age of the customer is greater than 10.

Figure: Message constraint

Message branching

Below figure "message branching" shows how "customer" object have two branches one is when the customer calls save data and one when he cancels the data.

Figure: Message branching

Doing Sequence diagram practically

Let's take a small example to understand sequence diagram practically. Below is a simple voucher entry screen for accounts data entry. Following are the steps how the accountant will do data entry for the voucher:-

Page 60

Page 61: OOPS Concepts

OOPS concept from C# Corner

Accountant loads the voucher data entry screen. Voucher screen loads with debit account codes and credit account codes in the respective combo boxes.

Accountant will then fill in all details of the voucher like voucher description, date, debit account code, credit account code, description, and amount and then click "add voucher" button.

Once "add voucher" is clicked it will appear in the voucher screen below in a grid and the voucher entry screen will be cleared and waiting for new voucher to be added. During this step voucher is not added to database it"s only in the collection.

If there are more vouchers to be added the user again fills voucher and clicks "add voucher". Once all the vouchers are added he clicks "submit voucher" which finally adds the group of vouchers to

the database.

Below figure "Voucher data entry screen" shows pictorially how the screen looks like.

Figure: Voucher data entry screen

Figure "Voucher data entry sequence diagram" shows how the sequence diagram looks like. Below diagram shows a full sequence diagram view of how the flow of the above screen will flow from the user interface to the data access layer. There are three main steps in the sequence diagram, let's understand the same step by step.

Page 61

Page 62: OOPS Concepts

OOPS concept from C# Corner

Step 1:- The accountant loads the voucher data entry screen. You can see from the voucher data entry screen image we have two combo boxes debit and credit account codes which are loaded by the UI. So the UI calls the "Account Master" to load the account code which in turn calls the data access layer to load the accounting codes.

Step 2:- In this step the accountant starts filling the voucher information. The important point to be noted in this step is that after a voucher is added there is a conditional statement which says do we want to add a new voucher. If the accountant wants to add new voucher he again repeats step 2 sequence in the sequence diagram. One point to be noted is the vouchers are not added to database they are added in to the voucher collection.

Step 3:- If there are no more vouchers the accountant clicks submit and finally adds the entire voucher in the database. We have used the loop of the sequence diagram to show how the whole voucher collection is added to the database.

Figure: Voucher data entry sequence diagram

Page 62

Page 63: OOPS Concepts

OOPS concept from C# Corner

Unified Modeling Language (UML): Part II

Introduction

Again I repeat do not think you get an architecture position by reading interview questions. But yes there should be some kind of reference which will help you quickly revise what are the definition. Just by reading these answers you get to a position where you are aware of the fundamentals. But if you have not really worked you will surely fail with scenario based questions. So use this as a quick revision rather than a short cut.

In case if you have not seen previous article Unified Modeling Language (UML): Part I, click here

Happy job hunting......

(I) Can you explain collaboration diagrams ?

Collaboration diagrams

Collaboration diagrams provide the same information as shown by sequence diagram but they show it in a different way. In sequence diagram we pay more attention to the time and sequence order, but in collaboration diagram we pay more emphasis on the interaction messages between the objects.

Figure 'Collaboration diagrams' shows how a collaboration diagram looks like. Below are some points you can easily pick up looking at the figure:-

Objects are represented in rectangle. Messages are represented by an arrow and sequence number. For instance in figure 'collaboration

diagrams' we can see the 'order product' has a arrow which shows that the message is sent from the customer object to the product and '1' represents that it's the first messages.

Conditional statements are denoted by square brackets '['. We can also group sequence numbers by grouping them using decimals. For instance 'Pay by master' and

'Pay by Visa' are all grouped in to message sequence number '3' ('Do payment'). So they are denoted by 3,3.1 and 3.2 respectively.

Page 63

Page 64: OOPS Concepts

OOPS concept from C# Corner

Figure: - Collaboration diagrams

You can represent the for each loop using the 'for each' keyword as shown in below figure 'for each in collaboration'.

Figure: - For each in collaboration

Note: - Try drawing a collaboration diagram for the same voucher data entry screen. Sequence and collaboration diagrams are also called as iteraction diagrams.

(I) Can you explain activity diagrams?

Activity diagrams

Activity diagram are used to capture complicated process flows in a system. Below figure 'Activity' shows a simple activity diagram. Some of the points which you can easily note from the activity diagram figure are:-

Start of an activity is denoted by a dark circle. End of an activity is denoted by a dark circle inside a white circle. Activities are denoted by simple oval rectangles.

Figure: - Activity

A decision in activity diagram is as shown figure 'Decision in Activity Diagram'. Figure shows the condition in a '[' (Square bracket). So the first activity is 'Check Age', if the age is greater than 16 then we can go for 'Adult Movie' activity or else we need to execute the 'Kids Movie' activity.

Page 64

Page 65: OOPS Concepts

OOPS concept from C# Corner

Figure: - Decision in Activity Diagram

There are situations in project where we need to execute two parallel activities in a project. A solid bold line represents from where the activities will split and execute in parallel and then again a solid line is where the parallel activities will meet. For instance in the below figure 'Parallel Processing' we can see how 'Make lemon juice' and 'Make Ginger Juice' activities are executed in parallel.

Page 65

Page 66: OOPS Concepts

OOPS concept from C# Corner

Figure: - Parallel Processing

In big and complex activity diagrams it's very difficult to figure out which object is responsible for which activities. This problem is solved by 'Swimlanes'. Consider the below figure 'Without Swimlanes'. The whole activity diagram looks very complex and it's very difficult to figure out which object is responsible for which activity.

Page 66

Page 67: OOPS Concepts

OOPS concept from C# Corner

Figure: - Without Swimlanes

Now see the below figure 'With Swimlanes' we have partitioned the activity to the respective objects like Customer, Stock, Order processing, Payment and Invoice. These partitions are termed as 'Swimlanes' , so if you feel that the activity diagram is complex think about using 'Swimlanes' it can really make your activity diagram readable.

Page 67

Page 68: OOPS Concepts

OOPS concept from C# Corner

Figure: - With Swimlanes

(I) What is state chart diagram?

State Chart Diagram

State diagram depicts different states that an object goes through during their life cycle. State diagram depicts how an object responds to events. We think state diagrams as optional and should be used if your project has scenarios where the object goes through lot of complicated states and transitions. If your project does not have such kind of scenarios then sequence, collaboration or activity would be sufficient to meet your needs. So all objects have states and an object moves from one state to other state when there is some event or transition.

There are three important things when we consider state of an object event, guard and action. Let's first define these three things: -

Action: - Action triggers an object state from one state to another. Event: - Event triggers the action. Guard: - Guard is condition on which it evaluates which action to be triggered.

These three things are principle component of state chart diagrams. Below figure 'Types of event and action' shows how they are represented in state chart diagrams.

Page 68

Page 69: OOPS Concepts

OOPS concept from C# Corner

Figure: - Types of Event and Action

There are three ways by which we can represent the same.

Type 1:- This methodology of writing is used when we need to map an event with action using a guard. For instance in the above figure 'Types of Event and Action' shows the event --> mouse click, guard --> double click and the resulting action --> open folder.

Type 2:- The guard is optional. For instance sometimes we only have events and actions, i.e. with out the guard. For instance when the even 'On' happens the action is that 'Light Bulb is on'.

Type 3:- This type of representation shows an infinite loop for an action. For instance the 'Watch will be running' infinitely during a state, as shown in figure 'Type of Event and Action'.

Now that we know how to write event, actions and guard, let's see how state diagram looks like. Below figure 'State example' shows how a state looks like. It's an oval rectangle as shown below. In order to show a transition we need to show an arrow from one state to other state as shown in figure 'State example'.

Page 69

Page 70: OOPS Concepts

OOPS concept from C# Corner

Figure: - State example

Below figure 'Sample state chart' shows a simple state chart diagram. Some points which are immediately visible from the diagrams are as follows:-

A dark black arrow indicates start of a state chart diagram. A dark circle with a white circle outside indicates end of a state chart diagram. Circular rectangle indicates state while arrows indicate events / transitions.

Figure: - Sample state chart

State is represented as shown in figure 'Basic element of state diagram'. It's a simple rectangle which is rounded. In the top section we give the state name. The below section is optional which has 'do/action'. It represents a long running activity when the object goes through this state.

(I) Can you explain stereotypes in UML?

Stereotypes are a way to define variations on existing UML model. This variation is brought in to place to extend UML in a consistent manner. They are displayed in double less than and double greater than sign with a simple text as shown below. The below figure shows at the left hand side a class diagram with out stereo types while the right hand side shows with stereo types. You can easily make out how the class diagram is readable with stereo types. For instance the 'Customer()' can be mistaken for a method but we have clarified that it's a constructor by using stereo types.

Page 70

Page 71: OOPS Concepts

OOPS concept from C# Corner

Figure: - Stereotypes

Below are some of the commonly used stereo types while writing UML.

<<Application>>:- Used to represent a UI system in a application.<<Database>> :- represents a database in a application.<<Table>> :- A table with in database.<<Library>> :- A reusable library or function.<<File>> :- Physical file on a folder.<<Executable>> :- A software component which can be executed.<<Web services>> :- Represents a web service.<<JDBC>> :- Java database connectivity , a JAVA API to connect to database.<<ODBC>> :- Open database connectivity , a Microsoft API to connect to database.

(I) Can you explain package diagrams?

Packages are like folders in a system which allows you to logically group UML diagrams. They make complex UML diagram readable. In actual projects they are used to logically group use cases and classes. So we can say there are two types of package diagrams one is class package diagram and other is use case package diagram. Package diagram depict a high level of overview for class and use cases.

Class package diagram: - Class package diagram are used to logical group classes. You can think that package technically map to 'Package' in JAVA and 'Namespaces' in C# and VB.NET. Packages are denoted by small rectangle on a big rectangle as shown in figure 'Package diagram'. One of the points to be noted is the stereotypes. We have numbered the figure so that we can understand it better.

1 - We are using the MVC (Model View controller) framework. So we have denoted this package using the << Framework >> stereo type. Refer the commonly used stereo type table discussed in the previous sections.

2 and 3 - 'Book tickets' is the second package which inherits from the MVC model. The stereo type is '<<application>>' which means it's a user interface.

4 - A simple line shows a link between two classes stating that one class package uses the other class package.

5 - This package is collection of the booking engine library.

6 - The final package is the database.

Page 71

Page 72: OOPS Concepts

OOPS concept from C# Corner

Figure: - Package diagram

As said before packages are nothing but collection of logical classes or any UML entity. We have shown the detail of the above package diagram. We should restrict from using package diagram for showing the in depth architecture as it can become very complicated. For instance the below diagram 'Detail Package diagram' shows how complicated it can look if use the package diagram to show in depth architecture. To avoid complication its good to only draw an over all diagram as shown in 'Package diagram'.

Figure: - Detail Package diagram

Page 72

Page 73: OOPS Concepts

OOPS concept from C# Corner

Use case package diagram: - The way we have logically grouped classes we can also use the package diagram to logically group use cases. Below figure shows how a use case package diagram looks like.

Figure: - Use Case Package

(B) Can you explain component diagrams?

Component diagrams achieve the same objective like package diagrams. They show the dependencies among software components. Below figure 'Component diagram' shows a sample component diagram for simple data entry application which uses a web service to interact with the database. We have numbered the steps to understand the details of the component diagram.

1 - Two rectangles are shown to represent a component of a system.2 - Stereo types are used to denote what kind of system it represents.3 - A line with a circle denotes an interface by which the external world can interact with the component. For instance in the figure we have represented a 'Customer Web service' which can is interacted by using XML.

Figure: - Component Diagram

(B) Can you explain deployment diagrams?

Deployment diagrams represents an overall static view of how software and hardware nodes in the application. They show what the hardware is and which components are installed on which hardware. In deployment diagram

Page 73

Page 74: OOPS Concepts

OOPS concept from C# Corner

we represent the hardware with a solid box and simple underlined text description showing which hardware is it. You can have more than one component on a single hardware. So the browser is an application UI which resides on the workstation computer and the database and web server resides on the web server hardware. Deployment diagram can be more complex with firewalls, payment gateways, PDA devices, VPN etc.

Figure: - Deployment diagram

(I) Can you explain how UML flows in actual project?

In actual projects we do not draw all the diagrams. Every UML diagram is made for a purpose. It completely depends on what's the nature of the project. In short you should ask yourself questions like, is this diagram important, what's my need etc. So below is a flow which you can follow in your project, again as we said it depends on what kind of scenario you want to depict.

Page 74

Page 75: OOPS Concepts

OOPS concept from C# Corner

Figure: - UML flow in actual projects

The first step is to derive use cases from the requirement documents. Once use cases are derived we need to decide the messages which will flow in the system. This can be

done using interaction diagrams. If you need to know the object creation life times we use the sequence diagram and if we want to concentrate on the messages we use the collaboration diagrams. So depending on scenario we need to make a choice which diagram we need to draw.

Now that we are clear about messages we can draw class diagrams to depict the static part of the project i.e. classes.

If we find any complicated class relationships we draw object diagrams. If we need to depict any complicated code we need to represent same with a activity diagram. Finally to give an overview of the project we can use package diagram, component or deployment

diagram. As said before we can use combination of component and deployment diagram to give a overview of the architecture.

Page 75

Page 76: OOPS Concepts

OOPS concept from C# Corner

Note: - Never say in a interview that we have used all UML diagrams in the technical document. It can give a very bad impression. As said every UML diagram is drawn according to the scenario of the project.

Page 76

Page 77: OOPS Concepts

OOPS concept from C# Corner

C# Heap(ing) Vs Stack(ing) in .NET: Part I

Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article I'll cover the basics of the Stack and Heap, types of variables and why some variables work as they do.

There are two places the .NET framework stores items in memory as your code executes. If you haven't already met, let me introduce you to the Stack and the Heap. Both the stack and heap help us run our code. They reside in the operating memory on our machine and contain the pieces of information we need to make it all happen.

Stack vs. Heap: What's the difference?

The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called"). The Heap is more or less responsible for keeping track of our objects (our data, well... most of it - we'll get to that later.).

Think of the Stack as a series of boxes stacked one on top of the next. We keep track of what's going on in our application by stacking another box on top every time we call a method (called a Frame). We can only use what's in the top box on the stack.done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to hold information (not keep track of execution most of the time) so anything in our Heap can be accessed at any time. With the Heap, there are no constraints as to what can be accessed like in the stack.Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet - we can grab what we need quickly.The Stack is like the stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.

The picture above, while not really a true representation of what's happening in memory, helps us distinguish a Stack from a Heap. The Stack is self-maintaining, meaning that it basically takes care of its own memory management. When the top box is no longer used, it's thrown out. The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean (no one wants dirty laundry laying around... it stinks!).

What goes on the Stack and Heap?

We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions.

Page 77

Page 78: OOPS Concepts

OOPS concept from C# Corner

Value Types:

In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):

bool byte char decimal double enum float int long sbyte short struct uint ulong ushort

Reference Types:

All the "things" declared with the types in this list are Reference types (and inherit from System.Object... except, of course, for object which is the System.Object object):

class interface delegate object string

Pointers:

The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type is means we access it through a Pointer.is a chunk of space in memory that points to another space in memory. A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null.

Page 78

Page 79: OOPS Concepts

OOPS concept from C# Corner

Instructions:

You'll see how the "Instructions" work later in this article...

How is it decided what goes where? (Huh?)

Ok, one last thing and we'll get to the fun stuff.

Here are our two golden rules:

1. A Reference Type always goes on the Heap - easy enough, right?

2. Value Types and Pointers always go where they were declared. This is a little more complex and needs a bit more understanding of how the Stack works to figure out where "things" are declared.

The Stack, as we mentioned earlier, is responsible for keeping track of where each thread is during the execution of our code (or what's been called). You can think of it as a thread "state" and each thread has its own stack. When our code makes a call to execute a method the thread starts executing the instructions that have been JIT compiled and live on the method table, it also putsmethod's parameters on the thread stack. Then, as we go through the code and run into variables within the method they are placed on top of the stack. This will be easiest to understand by example...

Take the following method.

public int AddFive(int pValue) { int result; result = pValue + 5; return result; }

Here's what happens at the very top of the stack. Keep in mind that what we are looking at is placed on top of many other items already living in the stack:

Page 79

Page 80: OOPS Concepts

OOPS concept from C# Corner

Once we start executin ghte method, the method's parameters are placed on the stack (we'll talk more about passing parameters later).

NOTE : the method does not live on the stack and is illustrated just for reference.

Next, control (the thread executing the method) is passed to the instructions to the AddFive() method which lives in our type's method table, a JIT compilation is performed if this is the first time we are hitting the method.

As the method executes, we need some memory for the "result" variable and it is allocated on the stack.

The method finishes execution and our result is returned.

Page 80

Page 81: OOPS Concepts

OOPS concept from C# Corner

And all memory allocated on the stack is cleaned up by moving a pointer to the available memory address where AddFive() started and we go down to the previous method on the stack (not seen here).

In this example, our "result" variable is placed on the stack. As a matter of fact, every time a Value Type is declared within the body of a method, it will be placed on the stack.

Now, Value Types are also sometimes placed on the Heap. Remember the rule, Value Types always go where they were declared?Well, if a Value Type is declared outside of a method, but inside a Reference Type it will be placed within the Reference Type on the Heap.

Here's another example.

If we have the following MyInt class (which is a Reference Type because it is a class):

public class MyInt { public int MyValue; }

and the following method is executing:

public MyInt AddFive(int pValue) { MyInt result = new MyInt(); result.MyValue = pValue + 5;

Page 81

Page 82: OOPS Concepts

OOPS concept from C# Corner

return result; }

Just as before, the thread starts executing the method and its parameters are placed on sthe thread's stack.

Now is when it gets interesting...

Because MyInt is a Reference Type, it is placed on the Heap and referenced by a Pointer on the Stack.

After AddFive() is finished executing (like in the first example), and we are cleaning up...

we're left with an orphaned MyInt in the heap (there is no longer anyone in the Stack standing around pointing to MyInt)!

Page 82

Page 83: OOPS Concepts

OOPS concept from C# Corner

This is where the Garbage Collection (GC) comes into play. Once our program reaches a certain memory threshold and we need more Heap space, our GC will kick off. The GC will stop all running threads (a FULL STOP), find all objects in the Heap that are not being accessed by the main program and delete them. The GC will then reorganize all the objects left in the Heap to make space and adjust all the Pointers to these objects in both the Stack and the Heap. As you can imagine, this can be quite expensive in terms of performance, so now you can see why it can be important to pay attention to what's in the Stack and Heap when trying to write high-performance code.

Ok... That great, but how does it really affect me?

Good question.

When we are using Reference Types, we're dealing with Pointers to the type, not the thing itself. When we're using Value Types, we're using the thing itself. Clear as mud, right?

Again, this is best described by example.

If we execute the following method:

public int ReturnValue() { int x = new int(); x = 3; int y = new int(); y = x; y = 4; return x; }

We'll get the value 3. Simple enough, right?

However, if we are using the MyInt class from before

public class MyInt { public int MyValue; }

Page 83

Page 84: OOPS Concepts

OOPS concept from C# Corner

and we are executing the following method:

public int ReturnValue2() { MyInt x = new MyInt(); x.MyValue = 3; MyInt y = new MyInt(); y = x; y.MyValue = 4; return x.MyValue; }

What do we get?... 4!

Why?... How does x.MyValue get to be 4?... Take a look at what we're doing and see if it makes sense:

In the first example everything goes as planned:

public int ReturnValue() { int x = 3; int y = x; y = 4; return x; }

In the next example, we don't get "3" because both variables "x" and "y" point to the same object in the Heap.

public int ReturnValue2() { MyInt x; x.MyValue = 3; MyInt y; y = x; y.MyValue = 4; return x.MyValue;

Page 84

Page 85: OOPS Concepts

OOPS concept from C# Corner

}

Hopefully this gives you a better understanding of a basic difference between Value Type and Reference Type variables in C# and a basic understanding of what a Pointer is and when it is used. In the next part of this series, we'll get further into memory management and specifically talk about method parameters.

Page 85

Page 86: OOPS Concepts

OOPS concept from C# Corner

C# Heap(ing) Vs Stack(ing) in .NET: Part II

Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article I'll cover some of the behaviors we need to be aware of when passing parameters to methods.

In Part I we covered the basics of the Heap and Stack functionality and where Variable Types and Reference Types are allocated as our program executes. We also covered the basic idea of what a Pointer is.

Parameters, the Big Picture.

Here's the detailed view of what happens as our code executes. We covered the basics of what happens when we make a method call in Part I. Let's get into more detail...

When we make a method call here's what happens:

1. Space is allocated for information needed for the execution of our method on the stack (called a Stack Frame). This includes the calling address (a pointer) which is basically a GOTO instruction so when the thread finishes running our method it knows where to go back to in order to continue execution.

2. Our method parameters are copied over. This is what we want to look at more closely.3. Control is passed to the JIT'ted method and the thread starts executing code. Hence, we have another

method represented by a stack frame on the "call stack".

The code:

public int AddFive(int pValue) { int result; result = pValue + 5; return result; }

Will make the stack look like this:

NOTE : the method does not live on the stack, and is illustrated here just for reference as the beginnnig of the stack frame. As discussed in Part I, Parameter placement on the stack will be handled differently depending on whether it is a

Page 86

Page 87: OOPS Concepts

OOPS concept from C# Corner

value type or a reference type. A value types is copied over and the reference of a reference type is copied over.ed over.

Passing Value Types.

Here's the catch with value types...

First, when we are passing a value types, space is allocated and the value in our type is copied to the new space on the stack. Look at the following method:

class Class1 { public void Go() { int x = 5; AddFive(x); Console.WriteLine(x.ToString()); } public int AddFive(int pValue) { pValue += 5; return pValue; }

}

As the method executes, space for "x" is placed on the stack with a value of 5.

Next, AddFive() is placed on the stack with space for it's parameters and the value is copied, bit by bit from x.

Page 87

Page 88: OOPS Concepts

OOPS concept from C# Corner

When AddFive() has finished execution, the thread is passed back to Go() and because AddFive() has completed, pValue is essentially "removed":

So it makes sense that the output from our code is "5", right? The point is that any value type parameters passed into a method are carbon copies and we count on the original variable's value to be preserved.

One thing to keep in mind is that if we have a very large value type (such as a big struct) and pass it to the stack, it can get very expensive in terms of space and processor cycles to copy it over each time. The stack does not have infinite space and just like filling a glass of water from the tap, it can overflow. A struct is a value type that can get pretty big and we have to be aware of how we are handling it.

Here's a pretty big struct:

public struct MyStruct { long a, b, c, d, e, f, g, h, i, j, k, l, m;

}

Take a look at what happens when we execute Go() and get to the DoSomething() method below:

public void Go() { MyStruct x = new MyStruct(); DoSomething(x); } public void DoSomething(MyStruct pValue) { // DO SOMETHING HERE....

Page 88

Page 89: OOPS Concepts

OOPS concept from C# Corner

}

This can be really inefficient. Imaging if we passed the MyStruct a couple thousand times and you can understand how it could really bog things down.

So how do we get around this problem? By passing a reference to the original value type as follows:

public void Go() { MyStruct x = new MyStruct(); DoSomething(ref x); } public struct MyStruct { long a, b, c, d, e, f, g, h, i, j, k, l, m; } public void DoSomething(ref MyStruct pValue) { // DO SOMETHING HERE....

}

This way we end up with more memory efficient allocation of our objects in memory.

The only thing we have to watch out for when passing our value type by reference is that we have access to the value type's value. Whatever is changed in pValue is changed in x. Using the code below, our results are going to

Page 89

Page 90: OOPS Concepts

OOPS concept from C# Corner

be "12345" because the pValue.a actually is looking at the memory space where our original x variable was declared.

public void Go() { MyStruct x = new MyStruct(); x.a = 5; DoSomething(ref x); Console.WriteLine(x.a.ToString()); } public void DoSomething(ref MyStruct pValue) { pValue.a = 12345;

}

Passing Reference Types.

Passing parameters that are reference types is similar to passing value types by reference as in the previous example.

If we are using the value type

public class MyInt { public int MyValue;

}

And call the Go() method, the MyInt ends up on the heap because it is a reference type:

public void Go() { MyInt x = new MyInt();

}

If we execute Go() as in the following code ...

Page 90

Page 91: OOPS Concepts

OOPS concept from C# Corner

public void Go() { MyInt x = new MyInt(); x.MyValue = 2; DoSomething(x); Console.WriteLine(x.MyValue.ToString()); } public void DoSomething(MyInt pValue) { pValue.MyValue = 12345;

}

Here's what happens...

1. Starting with the call to Go() the variable x goes on the stack.2. Starting with the call to DoSomething() the parameter pValue goes on the stack.3. The value of x (the address of MyInt on the stack) is copied to pValue

So it makes sense that when we change the MyValue property of the MyInt object in the heap using pValue and we later refer to the object on the heap using x, we get the value "12345".

So here's where it gets interesting. What happens when we pass a reference type by reference?

Check it out. If we have a Thing class and Animal and Vegetables are both things:

public class Thing { } public class Animal:Thing { public int Weight; } public class Vegetable:Thing

Page 91

Page 92: OOPS Concepts

OOPS concept from C# Corner

{ public int Length;

}

And we execute the Go() method below:

public void Go() { Thing x = new Animal(); Switcharoo(ref x); Console.WriteLine( "x is Animal : " + (x is Animal).ToString()); Console.WriteLine( "x is Vegetable : " + (x is Vegetable).ToString()); } public void Switcharoo(ref Thing pValue) { pValue = new Vegetable();

}

Our variable x is turned into a Vegetable.

x is Animal : Falsex is Vegetable : True

Let's take a look at what's happening:

1. Starting with the Go() method call, the x pointer goes on the stack2. The Animal goes on the hea

Page 92

Page 93: OOPS Concepts

OOPS concept from C# Corner

3. Starting with the call to Switcharoo() method, the pValue goes on the stack and points to x

4. The Vegetable goes on the heapthe heap5. The value of x is changed through pValue to the address of the Vegetable

If we don't pass the Thing by ref, we'll keep the Animal and get the opposite results from our code.

If the above code doesn't make sense, check out my article on types of Reference variables to get a better understanding of how variables work with reference types.

Page 93

Page 94: OOPS Concepts

OOPS concept from C# Corner

C# Heap(ing) Vs Stack(ing) in .NET: Part III

Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article we'll cover an issue that arises from having reference variables in the heap and how to fix it using ICloneable.

A Copy Is Not A Copy.

To clearly define the problem, let's examine what happens when there is a value type on the heap versus having a reference type on the heap. First we'll look at the value type. Take the following class and struct. We have a Dude class which contains a Name element and two Shoe(s). We have a CopyDude() method to make it easier to make new Dudes.

public struct Shoe{ public string Color; } public class Dude { public string Name; public Shoe RightShoe; public Shoe LeftShoe; public Dude CopyDude() { Dude newPerson = new Dude(); newPerson.Name = Name; newPerson.LeftShoe = LeftShoe; newPerson.RightShoe = RightShoe; return newPerson; } public override string ToString() { return (Name + " : Dude!, I have a " + RightShoe.Color + " shoe on my right foot, and a " + LeftShoe.Color + " on my left foot."); }

}

Our Dude class is a variable type and because the Shoe struct is a member element of the class they both end up on the heap.

Page 94

Page 95: OOPS Concepts

OOPS concept from C# Corner

When we run the following method:

public static void Main() { Class1 pgm = new Class1(); Dude Bill = new Dude(); Bill.Name = "Bill"; Bill.LeftShoe = new Shoe(); Bill.RightShoe = new Shoe(); Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue"; Dude Ted = Bill.CopyDude(); Ted.Name = "Ted"; Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red"; Console.WriteLine(Bill.ToString()); Console.WriteLine(Ted.ToString());

}

We get the expected output:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.

What happens if we make the Shoe a reference type? Herein lies the problem. If we change the Shoe to a reference type as follows:

public class Shoe{ public string Color;

}

and run the exact same code in Main(), look how our input changes:

Bill : Dude!, I have a Red shoe on my right foot, and a Red on my left footTed : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

Page 95

Page 96: OOPS Concepts

OOPS concept from C# Corner

The Red shoe is on the other foot. This is clearly an error. Do you see why it's happening? Here's what we end up with in the heap.

Because we now are using Shoe as a reference type instead of a value type and when the contents of a reference type are copied only the pointer is copied (not the actual object being pointed to), we have to do some extra work to make our Shoe reference type behave more like a value type.

Luckily, we have an interface that will help us out: ICloneable. This interface is basically a contract that all Dudes will agree to and defines how a reference type is duplicated in order to avoid our "shoe sharing" error. All of our classes that need to be "cloned" should use the ICloneable interface, including the Shoe class.

ICloneable consists of one method: Clone()

public object Clone() {

}

Here's how we'll implement it in the Shoe class:

public class Shoe : ICloneable { public string Color; #region ICloneable Members public object Clone() { Shoe newShoe = new Shoe(); newShoe.Color = Color.Clone() as string; return newShoe; } #endregion

}

Inside the Cone() method, we just make a new Shoe, clone all the reference types and copy all the value types and return the new object. You probably noticed that the string class already implements ICloneable so we can call

Page 96

Page 97: OOPS Concepts

OOPS concept from C# Corner

Color.Clone(). Because Clone() returns a reference to an object, we have to "retype" the reference before we can set the Color of the shoe.

Next, in our CopyDude() method we need to clone the shoes instead of copying them

public Dude CopyDude() { Dude newPerson = new Dude(); newPerson.Name = Name; newPerson.LeftShoe = LeftShoe.Clone() as Shoe; newPerson.RightShoe = RightShoe.Clone() as Shoe; return newPerson;

}

Now, when we run main:

public static void Main() { Class1 pgm = new Class1(); Dude Bill = new Dude(); Bill.Name = "Bill"; Bill.LeftShoe = new Shoe(); Bill.RightShoe = new Shoe(); Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue"; Dude Ted = Bill.CopyDude(); Ted.Name = "Ted"; Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red"; Console.WriteLine(Bill.ToString()); Console.WriteLine(Ted.ToString());

}

We get:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left footTed : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

Which is what we want.

Page 97

Page 98: OOPS Concepts

OOPS concept from C# Corner

Wrapping Things Up.

So as a general practice, we want to always clone reference types and copy value types. (It will reduce the amount of aspirin you will have to purchase to manage the headaches you get debugging these kinds of errors.)

So in the spirit of headache reduction, let's take it one step further and clean up the Dude class to implement ICloneable instead of using the CopyDude() method.

public class Dude: ICloneable { public string Name; public Shoe RightShoe; public Shoe LeftShoe; public override string ToString() { return (Name + " : Dude!, I have a " + RightShoe.Color + " shoe on my right foot, and a " + LeftShoe.Color + " on my left foot."); } #region ICloneable Members public object Clone() { Dude newPerson = new Dude(); newPerson.Name = Name.Clone() as string; newPerson.LeftShoe = LeftShoe.Clone() as Shoe; newPerson.RightShoe = RightShoe.Clone() as Shoe; return newPerson; } #endregion

}

And we'll change the Main() method to use Dude.Clone()

public static void Main() {

Page 98

Page 99: OOPS Concepts

OOPS concept from C# Corner

Class1 pgm = new Class1(); Dude Bill = new Dude(); Bill.Name = "Bill"; Bill.LeftShoe = new Shoe(); Bill.RightShoe = new Shoe(); Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue"; Dude Ted = Bill.Clone() as Dude; Ted.Name = "Ted"; Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red"; Console.WriteLine(Bill.ToString()); Console.WriteLine(Ted.ToString());

}

And our final output is:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.

So all is well.

Something interesting to note is that the assignment operator (the "=" sign) for the System.String class actually clones the string so you don't have to worry about duplicate references. However you do have to watch our for memory bloating. If you look back at the diagrams, because the string is a reference type it really should be a pointer to another object in the heap, but for simplicity's sake, it's shown as a value type.

In Conclusion.

As a general practice, if we plan on ever copying of our objects, we should implement (and use) ICloneable. This enables our reference types to somewhat mimic the behavior of a value type. As you can see, it is very important to keep track of what type of variable we are dealing with because of differences in how the memory is allocated for value types and reference types.

In the next article, we'll look at a way to reduce our code "footprint" in memory.

C# Heap(ing) Vs Stack(ing) in .NET: Part IV

Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article we'll look into Garbage Collection (GC) and some ways to keep our applications running efficiently.

Page 99

Page 100: OOPS Concepts

OOPS concept from C# Corner

Graphing

Let's look at this from the GC's point of view. If we are responsible for "taking out the trash" we need a plan to do this effectively. Obviously, we need to determine what is garbage and what is not (this might be a bit painful for the pack-rats out there).

In order to determine what needs to be kept, we'll first make the assumption that everything not being used is trash (those piles of old papers in the corner, the box of junk in the attic, everything in the closets, etc.) Imagine we live with our two good friends: Joseph Ivan Thomas (JIT) and Cindy Lorraine Richmond (CLR). Joe and Cindy keep track of what they are using and give us a list of things they need to keep. We'll call the initial list our "root" list because we are using it as a starting point. We'll be keeping a master list to graph where everything is in the house that we want to keep. Anything that is needed to make things on our list work will be added to the graph (if we're keeping the TV we don't throw out the remote control for the TV, so it will be added to the list. If we're keeping the computer the keyboard and monitor will be added to the "keep" list).

This is how the GC determines what to keep as well. It receives a list of "root" object references to keep from just-in-time (JIT) compiler and common language runtime (CLR) (Remember Joe and Claire?) and then recursively searches object references to build a graph of what should be kept.

Roots consist of:

Global/Static pointers. One way to make sure our objects are not garbage collected by keeping a reference to them in a static variable.

Pointers on the stack. We don't want to throw away what our application's threads still need in order to execute.

CPU register pointers. Anything in the managed heap that is pointed to by a memory address in the CPU should be preserved (don't throw it out).

In the above diagram, objects 1, 3, and 5 in our managed heap are referenced from a root 1 and 5 are directly referenced and 3 is found during the recursive search. If we go back to our analogy and object 1 is our television, object 3 could be our remote control. After all objects are graphed we are ready to move on to the next step, compacting.

Compacting

Now that we have graphed what objects we will keep, we can just move the "keeper objects" around to pack things up.

Page 100

Page 101: OOPS Concepts

OOPS concept from C# Corner

Fortunately, in our house we don't need to clean out the space before we put something else there. Since Object 2 is not needed, as the GC we'll move Object 3 down and fix the pointer in Object 1.

Next, as the GC, we'll copy Object 5 down

Now that everything is cleaned up we just need to write a sticky note and put it on the top of our compacted heap to let Claire know where to put new objects.

Page 101

Page 102: OOPS Concepts

OOPS concept from C# Corner

Knowing the nitty-gritty of CG helps in understanding that moving objects around can be very taxing. As you can see, it makes sense that if we can reduce the size of what we have to move, we'll improve the whole GC process because there will be less to copy.

What about things outside the managed heap?

As the person responsible for garbage collection, one problem we run into in cleaning house is how to handle objects in the car. When cleaning, we need to clean everything up. What if the laptop is in the house and the batteries are in the car?

There are situations where the GC needs to execute code to clean up non-managed resources such as files, database connections, network connections, etc. One possible way to handle this is through a finalizer.

class Sample{ ~Sample() { // FINALIZER: CLEAN UP HERE }}

During object creation, all objects with a finalizer are added to a finalization queue. Let's say objects 1, 4, and 5 have finalizers and are on the finalization queue. Let's look at what happens when objects 2 and 4 are no longer referenced by the application and ready for garbage collection.

Page 102

Page 103: OOPS Concepts

OOPS concept from C# Corner

Object 2 is treated in the usual fashion. However, when we get to object 4, the GC sees that it is on the finalization queue and instead of reclaiming the memory object 4 owns, object 4 is moved and it's finalizer is added to a special queue named freachable.

There is a dedicated thread for executing freachable queue items. Once the finalizer is executed by this thread on Object 4, it is removed from the freachable queue. Then and only then is Objet 4 ready for collection.

So Object 4 lives on until the next round of GC.

Page 103

Page 104: OOPS Concepts

OOPS concept from C# Corner

Because adding a finalizer to our classes creates additional work for GC it can be very expensive and adversely affect the performance garbage collection and thus our program. Only use finalizers when you are absolutely sure you need them.

A better practice is to be sure to clean up non-managed resources. As you can imagine, it is preferable to explicitly close connections and use the IDisposable interface for cleaning up instead of a finalizer where possible.

IDisposaible

Classes that implement IDisposable perform clean-up in the Dispose() method (which is the only signature of the interface). So if we have a ResouceUser class instead of using a finalizer as follows:

public class ResourceUser{ ~ResourceUser() // THIS IS A FINALIZER { // DO CLEANUP HERE }}

We can use IDisposable as a better way to implement the same functionality:

public class ResourceUser : IDisposable{ #region IDisposable Members public void Dispose() { // CLEAN UP HERE!!! } #endregion}

IDisposable in integrated with the using keyword. At the end of the using block Dispose() is called on the object declared in using(). The object should not be referenced after the using block because it should be essentially considered "gone" and ready to be cleaned up by the GC.

public static void DoSomething(){ResourceUser rec = new ResourceUser(); using (rec){ // DO SOMETHING } // DISPOSE CALLED HERE // DON'T ACCESS rec HERE

Page 104

Page 105: OOPS Concepts

OOPS concept from C# Corner

}

I like putting the declaration for the object in the using block because it makes more sense visabally and rec is no longer available outside of the scope of the using block. Whis this pattern is more in line with the intention of the IDisposible interface, it is not required.

public static void DoSomething(){using (ResourceUser rec = new ResourceUser()){ // DO SOMETHING } // DISPOSE CALLED HERE}

By using using() with classes that implement IDisposible we can perform our cleanup without putting additional overhead on the GC by forcing it to finalize our objects.

Static Variables: Watch Out!

class Counter{ private static int s_Number = 0; public static int GetNextNumber() { int newNumber = s_Number; // DO SOME STUFF s_Number = newNumber + 1; return newNumber; }}

If two threads call GetNextNumber() at the same time and both are assigned the same value for newNumber before s_Num}

If two threads call GetNextNumber() at the same time and both are assigned the same value for newNumber before s_Number is incremented they will return the same result!word is one way to ensure only one thread can access a block of code at a time. As a best practice, you should lock as little code as possible because threads have to wait in a queue to execute the code in the lock() block and it can be inefficient.

class Counter{ private static int s_Number = 0; public static int GetNextNumber() {

Page 105

Page 106: OOPS Concepts

OOPS concept from C# Corner

lock (typeof(Counter)) { int newNumber = s_Number; // DO SOME STUFF newNumber += 1; s_Number = newNumber; return newNumber; } }}

Static Variables: Watch Out... Number 2!

The next thing we have to watch out for objects referenced by static variables. Remember, how anything that is referenced by a "root" is not cleaned up. Here's one of the ugliest examples I can come up with:

class Olympics{ public static Collection<Runner> TryoutRunners;} class Runner{ private string _fileName; private FileStream _fStream; public void GetStats() { FileInfo fInfo = new FileInfo(_fileName); _fStream = _fileName.OpenRead(); }}

Because the Runner Collection is static for the Olympics class, not only will objects in the collection will not be released for garbage collection (they are all indirectly referenced through a root), but as you probably noticed, every time we run GetStats() the stream is opened to the file. Because it is not closed and never released by GC this code is effectively a disaster waiting to happen. Imagine we have 100,000 runners trying out for the Olympics. We would end up with that many non-collectable objects each with an open resource. Ouch! Talk about poor performance!

Singleton

One trick to keep things light is to keep only one instance of a class in memory at all times. To do this we can use the GOF Singleton Pattern.

One trick to keep things light is to keep only one instance of a utility class in memory at all times. One easy way to do this we can use the GOF Singleton Pattern. Singletons should be used with caution because they are really "global variables" and cause us much headached and "strange" behavior in multi-threaded applications where

Page 106

Page 107: OOPS Concepts

OOPS concept from C# Corner

different threads could be altering the state of the object. If we are using the singleton pattern (or any global variable) we should be able to justify it (in other words... don't do it without a good reason).

public">{ private static Earth _instance = new Earth(); private Earth() { } public static Earth GetInstance() { return _instance; }}

We have a private constructor so only Earth can execute it's constructor and make an Earth. We have a static instance of Earth and a static method to get the instance. This particular implementation is thread safe because the CLR ensures thread safe creation of static variables. This is the most elegant way I have found to implement the singleton pattern in C#.

In Conclusion...

So to wrap up, some things we can do to improve GC performance are:

1. Clean up. Don't leave resources open! Be sure to close all connections that are opened and clean up all non-managed objects as soon as possible. As a general rule when using non-managed objects, instantiate as late as possible and clean up as soon as possible.

2. Don't overdo references. Be reasonable when using references objects. Remember, if our object is alive, all of it's referenced objects will not be collected (and so on, and so on). When we are done with something referenced by class, we can remove it by either setting the reference to null. One trick I like to do is setting unused references to a custom light weight NullObject to avoid getting null reference exceptions. The fewer references laying about when the GC kicks off, the less pressure the mapping process will be.

3. Easy does it with finalizers. Finalizers are expensive during GC we should ONLY use them if we can justify it. If we can use IDisposible instead of a finalizer, it will be more efficient because our object can be cleaned up in one GC pass instead of two.

4. Keep objects and their children together. It is easier on the GC to copy large chunks of memory together instead of having to essentially de-fragment the heap at each pass, so when we declare a object composed of many other objects, we should instantiate them as closely together as possible.

Page 107