You are on page 1of 136

Why we use OOPS concepts, What is its advantage? WE use OOP because it supports polymorphism, inheritance, encapsulation.

Inheritance provide reusing the defined the code without rewriting them and as well we can write in them new fields and methods. Encapsulation provide data hiding or data security, . It also supports combining the variables and their methods in a single class. It also supports modification in coding without complexity. Because of Encapsulation, The Error can be detected easily. Polymorphism at run time supports assigning a relative object at run time. It also supports method overriding that is same method name with diff. no of parameters or with parameters with diff. data types.

Why we use OOPS concepts, What is its advantage


oops stands for object oriented programming.It supports abstraction,encapsulation.The concepts of classes and objects hav made OOPS very unique.C++,java are eg of OOPS.Advantages1)Encapsulation-i.e Data hiding ,programmer can ensure that his code is not accessed.Access specifiers like protected,private etc help the purpose2)inheritance-helps in code reusability]3)polymorphism]4)abstraction Advantage of OOP: 1. Through inheritance we can achieve reusability. Also eliminate redundant code. 2. The principle of data hiding helps to build secure program. 3. Since java objects represent real world object, so oops provide a clear structure of the program which becomes easy to map real world problem and give solution. 4. It enhances program modularity since each object exists independently.

why we are using OOPS?


We use oops as it supports unique concepts such as classes and objects.Oops handles concepts such as Data Encapsulation & Data Hiding, it also involves Inheritance and Polymorphism.By using oops the programmer can ensure that his code is not accessed by using Access specifiers like protected,private etc.It enhances program modularity since each object exists independently. .C++,java are eg of OOPS OOPS is nothing but object oriented programming language, nothing but pure java objects . Here we are creating the object inside the class.It provides the set of

features included Inheritance, Polymorphism, Abstraction , Encapsulation. These features are accessed through only objects. (ie., objects are created in our classes and implement the mechanism for the features , we can access all the methods and variable through the objects only)

OOPS Concepts
Object-oriented programming (OOP) is a computer science term used to characterize a programming language that began development in the 1960s. The term object-oriented programming was originally coined by Xerox PARC to designate a computer application that describes the methodology of using objects as the foundation for computation. By the 1980s, OOP rose to prominence as the programming language of choice, exemplified by the success of C++. Currently, OOPs such as Java, J2EE, C++, C#, Visual Basic.NET, Python and JavaScript are popular OOP programming languages that any career-oriented Software Engineer or developer should be familiar with. OOP is widely accepted as being far more flexible than other computer programming languages. OOPs use three basic concepts as the fundamentals for the programming language: classes, objects and methods. Additionally, Inheritance, Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within object-oriented programming languages that are explained in online tutorials describing the functionality of each concept in detail. High-end jobs with well-paid salaries are offered around the world for experts in software development using object-oriented programming languages. The OOPs concepts described and explained in easy to use, step-by-step, practical tutorials will familiarize you with all aspects of OOPs. Oops FAQ Oops Interview Questions
Training Index

OOPS Tutorials Object-oriented programming OOP is a computer science term used to characterize a programming language that began development in the 1960 s. The term object-oriented programming was originally coined by Xerox PARC to designate a computer application that describes the methodology of using objects as the foundation for computation. Object Oriented Programming Introduction

Object Oriented Programming Introduction Object Oriented Programming also known as OOP is a computer science term which is used to describe a computer application that is composed of multiple objects which are connected to each other. Traditionally most computer programming languages were simply a group of functions or instructions. With OOP Object Oriented Programming Concepts Object Oriented Programming Concepts Three of the most basic concepts object oriented programming are Classes Objects and Methods. However there a few more concepts that you will want to become familiar with. These Inheritance Abstraction Polymorphism Event and Encapsulation. In this article I be using the class Cats as an What is Object Oriented Programming? What is Object Oriented Programming There are a number of common characteristics which are found in object oriented programming languages. Some of these are the grouping of data and functions a separation of the interface with the implementation and the sharing of code. At the most basic level object oriented programming is a different method The History of Object Oriented Programming The History of Object Oriented Programming The basis for OOP started in the early 1960s. A breakthrough involving instances and objects was achieved at MIT with the PDP-1 and the first programming language to use objects was Simula 67. It was designed for the purpose of creating simulations and was developed by Kristen Nygaard and Ole-Johan Dahl Object Oriented Programming Object Oriented Programming Traditionally programming languages have been divided into two categories and these are data and procedures which are carried out on data. By itself data is static. It will not be static when procedures are carried out which can alter it. The functions and processes that work on data are only useful because they can Object Oriented Programming Overview Object Oriented Programming Overview If you are not familiar with an objectoriented programming language you will first need to understand the foundation that makes up this paradigm. It is a necessity for anyone who plans on writing code. In this article I will explain the basic OOP structures in detail. The first thing that you will want to for are are will

The Importance of Inheritance Within OOP The Importance of Inheritance Within OOP In an object-oriented programming language that is well designed a function should be able to have functions that reside inside it. In addition to this other functions should be processed as input and output as well. When an OOP language uses these features it will utilize a design that is simple and consistent. This The Inheritance Concept in OOPs The Inheritance Concept In OOPs In object oriented programming objects will be characterised by classes. It is possible to learn a lot about an object based on the class it belongs to. Even if you are not familiar with the name Maybach If I told you it is a car you would immediately know that it has four wheels an engine and doors. Objected oriented A Object Oriented Programming Lesson for Beginners A Object Oriented Programming Lesson For Beginners In this article I will go over object oriented programming in relation to PHP. This article will be especially useful to those who already have a simple knowledge of programming and variables. You should know what a variable is and you should also know about the different types of variables. When The Use of Access Specifiers in Object Oriented Programming The Use of Access Specifiers In Object Oriented Programming In object oriented programming a variable will have a certain range. This range can be defined as the place where it can be viewed. In most cases there are two simple models that are used and these are lexically scoped and dynamically scoped. Dynamic scoping is a system which is based Class-based Object Oriented Programming Class-based Object Oriented Programming Class-based object oriented programming is a style that gains inheritance by processing classes as objects. The most prominent style of OOP is class-based instead of object-based. With the class-based OOP system objects are units that merge states identities and behaviors. The foundation and behavior of The OOP Paradigm The OOP Paradigm Object oriented programming is a concept that was created because of the need to overcome the problems that were found with using structured programming techniques. While structured programming uses an

approach which is top down OOP uses an approach which is bottom up. Traditionally programming has placed an emphasis on logic and Object Oriented Programming As a Paradigm Object Oriented Programming As a Paradigm There has been debate about the proper definition to give to object oriented programming. There has also been some debate about the primary idea behind the concept. In a nutshell object oriented programming is the technique of writing application text that is split into a number of modules. Object oriented Object Oriented Programming Lessons Object Oriented Programming Lessons If you are familiar with the programming field it is likely that you have heard people talking about object oriented programming languages. If Java is the first programming language you have worked with you are probably wandering why so many people are talking about it. If you have worked with Java you should Understanding Classes Within Object Oriented Programming Understanding Classes Within Object Oriented Programming To fully understand object oriented programming you will want to be familiar with classes. When you look at the world around you it will become obvious that many objects are the same type. For example the car you drive is just one of the millions of cars that exist in the world. In the OOP Understanding The Message Concept in OOPs Understanding The Message Concept In OOPs To understand object oriented programming you will need to become familiar with messages. As the name implies a message is a process in which software objects will communicate with one another. Because of this having one object is not enough. An object will work best when it is exists in a large application Object Oriented Programming Issues Object Oriented Programming Issues There are a number of errors that programmers can make when they are using an object oriented programming languages. One example of this is looking at the type of object instead of the membership it is associated with. When this happens the advantages of polymorphism and inheritance are weakened. This is just one Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

OOPS Concepts

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

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

Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit. Example for encapsulation is class. A class can contain data structures and methods. Consider the following class public class Aperture

{ public Aperture () { } protected double height; protected double width; protected double thickness; public double get volume() { Double volume=height * width * thickness; if (volume<0) return 0; return volume; } } In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction:
Abstraction is a process of hiding the implementation details and displaying the essential features. Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speakers works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone. So here the Laptop is an object that is designed to hide its complexity. How to abstract: - By using Access Specifiers

.Net has five access Specifiers


Public -- Accessible outside the class through object reference. Private -- Accessible inside the class only through member functions. Protected -- Just like private but Accessible in derived classes also through member functions. Internal -- Visible inside the assembly. Accessible through objects. Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions. Lets try to understand by a practical example:-

public class Class1 { int i; //No Access specifier means private public int j; // Public protected int k; //Protected data internal int m; // Internal means visible inside assembly protected internal int n; //inside assembly as well as to derived classes outside assembly static int x; // This is also private public static int y; //Static means shared across objects [DllImport("MyDll.dll")] public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly public void myFoo2() { //Within a class if you create an object of same class then you can access all data members through object reference even private data too Class1 obj = new Class1(); obj.i =10; //Error cant access private data through object.But here it is accessible.:) obj.j =10; obj.k=10; obj.m=10; obj.n=10; // obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10; } } Now lets try to copy the same code inside Main method and try to compile [STAThread] static void Main() { //Access specifiers comes into picture only when you create object of class outside the class Class1 obj = new Class1(); // obj.i =10; //Error cant access private data through object. obj.j =10; // obj.k=10; //Error cant access protected data through object. obj.m=10; obj.n=10; // obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; //Error cant access private data outside class // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10; } What if Main is inside another assembly [STAThread]

static void Main() { //Access specifiers comes into picture only when you create object of class outside the class Class1 obj = new Class1(); // obj.i =10; //Error cant access private data through object. obj.j =10; // obj.k=10; //Error cant access protected data through object. // obj.m=10; // Error cant access internal data outside assembly // obj.n=10; // Error cant access internal data outside assembly obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; //Error cant access private data outside class // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10; } In object-oriented software, complexity is managed by using abstraction. Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details. //

Inheritance:
Inheritance is a process of deriving the new class from already existing class C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.

Using System; Public class BaseClass { Public BaseClass () { Console.WriteLine ("Base Class Constructor executed"); } Public void Write () { Console.WriteLine ("Write method in Base Class executed"); } } Public class ChildClass: BaseClass { Public ChildClass () { Console.WriteLine("Child Class Constructor executed"); }

Public static void Main () { ChildClass CC = new ChildClass (); CC.Write (); }

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass. The output of the above program is Output: Base Class Constructor executed Child Class Constructor executed Write method in Base Class executed this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes. In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name. Syntax: class ChildClassName: BaseClass { //Body } C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time error: Class 'C' cannot have multiple base classes: 'A' and 'B'. public class A { } public class B { } public class C : A, B { } In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method(). Note: Classes can inherit from multiple interfaces at the same time. Interview Question:

How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article. Using System; Public class A { Public void A_Method () { Console.WriteLine ("Class A Method Called"); } } Public class B: A { Public void B_Method () { Console.WriteLine ("Class A Method Called"); } } Public class C: B { Public void C_Method () { Console.WriteLine ("Class A Method Called"); } Public static void Main () { C C1 = new C (); C1.A_Method (); C1.B_Method (); C1.C_Method (); }

} When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.

Common Interview Question: Are private class members inherited to the derived
class? Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error. Using System; Public class A { Public void M1 () { }

Private void M2 () { } } Public class B: A { Public static void Main () { B B1 = new B (); B1.M1 (); //Error, Cannot access private member M2 //B1.M2 (); } } Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding. If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.

Using System; Public class Parent { Public void Write () { Console.WriteLine ("Parent Class write method"); } } Public class Child: Parent { Public new void Write () { Console.WriteLine ("Child Class write method"); } Public static void Main () { Child C1 = new Child (); C1.Write (); //Type caste C1 to be of type Parent and call Write () method ((Parent) C1).Write (); }

Polymorphism:

When a message can be processed in different ways is called polymorphism. Polymorphism means many forms. Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features:


It allows you to invoke methods of derived class through base class reference during runtime. It has the ability for classes to provide different implementations of methods that are called through the same name.

Polymorphism is of two types:


1. Compile time polymorphism/Overloading 2. Runtime polymorphism/Overriding

Compile Time Polymorphism


Compile time polymorphism is method and operators overloading. It is also called early binding. In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism


Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype. Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar. Method overloading has nothing to do with inheritance or virtual methods. Following are examples of methods having different overloads: void area(int side); void area(int l, int b); void area(float radius); Practical example of Method Overloading (Compile Time Polymorphism) using System; namespace method_overloading

class Program { public class Print { public void display(string name) { Console.WriteLine ("Your name is : " + name); } public void display(int age, float marks) { Console.WriteLine ("Your age is : " + age); Console.WriteLine ("Your marks are :" + marks); } } static void Main(string[] args) { Print obj = new Print (); obj.display ("George"); obj.display (34, 76.50f); Console.ReadLine ();

} } }

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters. When and why to use method overloading Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task. You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing. Method overloading showing many forms. using System; namespace method_overloading_polymorphism { Class Program { Public class Shape { Public void Area (float r) {

float a = (float)3.14 * r; // here we have used function overload with 1 parameter. Console.WriteLine ("Area of a circle: {0}",a);

Public void Area(float l, float b) { float x = (float)l* b; // here we have used function overload with 2 parameters. Console.WriteLine ("Area of a rectangle: {0}",x); } public void Area(float a, float b, float c) { float s = (float)(a*b*c)/2; // here we have used function overload with 3 parameters. Console.WriteLine ("Area of a circle: {0}", s); }

} }

Static void Main (string[] args) { Shape ob = new Shape (); ob.Area(2.0f); ob.Area(20.0f,30.0f); ob.Area(2.0f,3.0f,4.0f); Console.ReadLine (); }

Things to keep in mind while method overloading If you use overload for method, there are couple of restrictions that the compiler imposes. The rule is that overloads must be different in their signature, which means the name and the number and type of parameters. There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

Method Overriding:
Whereas Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords. Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.

Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called. Example: // Base class public class BaseClass { public virtual void Method1() { Console.Write("Base Class Method"); } } // Derived class public class DerivedClass : BaseClass { public override void Method1() { Console.Write("Derived Class Method"); } } // Using base and derived class public class Sample { public void TestMethod() { // calling the overriden method DerivedClass objDC = new DerivedClass(); objDC.Method1(); // calling the baesd class method BaseClass objBC = (BaseClass)objDC; objDC.Method1(); } } Output --------------------Derived Class Method Derived Class Method

Constructors and Destructors:


Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects. Constructors and destructors do not have return types nor can they return values.

References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared const, or volatile. Unions cannot contain class objects that have constructors or destructors.

Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects. The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator. Example of Constructor class C { private int x; private int y; public C (int i, int j) { x = i; y = j; } public void display () { Console.WriteLine(x + "i+" + y); } } Example of Destructor class D { public D () { // constructor } ~D () { // Destructor } }

Object Oriented Concepts in C#


In this article we will discuss key concepts of object orientation with their practical implementation in C#. We will discuss here basics of OOPS

including Interfaces, Access Modifiers, inheritance, polymorphism etc. This is my second article on csharp-corner.com. My first article was "Memory Management in .NET", you can find this article at http://www.c-sharpcorner.com/ UploadFile/tkagarwal/ MemoryManagementInNet11232005064832AM/ MemoryManagementInNet.aspx Key Concepts of Object Orientation

Abstraction 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. 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.

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:

1. Interface 2. Implementation or Behavior 3. 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 implementationas 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 semanticmeaning 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. 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 { 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 { 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(); }

Output Name: John L. Malgraine SSN: 444-55-6666 Employee 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) { } }

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 class MyDerived 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 { 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() { 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 memberMyObject.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. 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 example using System; public class Employee { public string name; 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. Trainer Alias: jtrainer Taxes: $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:
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() { // 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

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 { 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 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 thirdparty 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:
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 { 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 Results Console.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 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. 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.

C# and oops concepts-keywords C# and oops concepts-keywords


Method: A method is a code block containing a series of statements.

Method hiding: If we are deriving a class from another class, then we can hide methods in the first class by defining the method in the second class with keyword new with same name as in first class. This process is called method hiding of first class. For example: new public void say hello() {------------} Method overriding: In derived classes we can override the method in first class by using keywords virtual for first class and override in second class. For example: public virtual say hello() {--------} Public override void say hello() {--------} Heap: Stores big things. Structure: For small objects or variables. Int, float, char, double etc. Class: Collection of methods and data. For huge objects or variables. String is the only class in primitive data types. Boxing: Conversion of value type data to referenced type data is called boxing. Namespace: Collection of many classes Sealed: If we use keyword sealed for a class, then we cannot inherit that class further. Static: Escape characters: Characters used for creating tab, for next line, single quotes and double quote etc are called escape characters. Ex: \+ tab \n next line \ double quotes \ single quotes \0 null

\v vertical tab Arithmetic operators: The operators which are used for performing arithmetic operations are called arithmetic operators. Ex: + - * / Logical operators: Operators which perform logical operations such as and or nand nor etc are called logical operators. Ex: && and operator || or operator Conditional operators: Operator which are used in conditional statements are called conditional operators. Ex: == ,>=, <=, !=. Jump instructions: The instructions which are used jumping from one part of program to another part while execution are called jump instructions. Ex: break, continue, goto. Ternary operator: the operator with syntax condition? Trueval : falseval Ex: maxval = a>b?a:b; Constant datatype: The datatype in which a value is given to a variable and cannot be changed further in program. Ex: const int pi= 3.14; Readonly datatype: The datatype in which if we define pi = 3.14 in middle of the code then we cannot change that value from that point. Access modifiers: Private: If we define a variable in a class as private, then we cannot use that variable further more in any different class. Public: If we define a variable in a class as public, then we can use that variable further more in any class. Internal: If we declare a variable as internal, then we can use this variable with in the library. This access modifier can only be used for library functions. Protected: If we use a protected access modifier for a variable or method, then they can be accessible by their inherited classes only.

Protected internal: This is same as protected but the only difference is, it is useful only in libraries. OOPS concepts: Encapsulation: The process of making variables and methods defined in a class accessible by main class is called encapsulation. In this process access modifiers like private, public and internal are used. Inheritance: If a class is inherited from another class then this property is called inheritance. The inherited class will have all the properties of the class from which it was inherited. Ex: class Honda {----------} Class accord: Honda {------------} Abstraction: Abstraction is the process in which if we dont define a function in a class, then we can give that functions definition in its inherited class. This process is called abstraction. In this abstraction we define mainly four terms. Abstract method:- The method in which only function is defined but no implementation is given to the function is called abstract method. Abstract class:- The class in which abstract methods are present is called abstract class. Pure abstract class:- The class in which only functions are defined but no implementation is given to any function is called pure abstraction class. Interface:- This is same as pure abstract class but it defined with keyword Interface instead of class. The only difference between pure abstract class and interface is for interface we can create multiple instances for inherited class. Doubt. Polymorphism:- If we use same name for different methods by passing different parameters by varying datatypes, then this process is called polymorphism. Ex:Class drawing {

Draw(int a){--------} Draw(int a, int b){--------} Draw(inta, string b){---------}etc ARRAYS: Single dimensional arrays:- The array with one dimension is called is called single dimensional array. The syntax for creating instance is test[ ] varname = new test[ ] . Ex: for integer array int[ ] a = new int [5]; For above example we are creating an array of 5 elements which is assigned to variable a. The length of the array can be determined using a.length condition. Multi dimensional arrays:- The array with multi dimensions is called multidimensional arrays. Ex: the syntax for multi dimensional array instances is going to be like this Int [ , ] num = new int [3,2]; The length of the array can be determined with expressions num.length(0) and num.length(1) Jagged arrays: The array with rows of different number of elements is called jagged arrays. Ex:- int [ ] [ ] num = new int [3] [ ] Num.length gives total number of rows. Num[1].length gives total num of elements in first row. Enum:- it automatically assigns numbers to the variable specified under the function. Ex: enum { Jan; Feb; Mar;

} It assigns jan with 0 and feb with 1 and mar with 2.


When we will use an Interface and Abstract class?

We do implement a interface when we want to add a specific characteristic to a class like if we want a particular human being is a singer then we can implement the singer interface to add this characteristic to a particular person.Interface implementation doesn't come under inheritance tree. But when we want to form a prototype of something so that other class can give its implementation we go for abstract class.

Insert, Select, Update and Delete Records in a Single Stored Procedure Using SQL Server
Background Sometimes there is a need to insert, select, update and delete records from a table using a single Stored Procedure instead of creating separate Stored Procedures for each operation. Suppose I have one .aspx web page in which I need a to insert, select, update and delete records. To do that instead of creating four Stored Procedures to perform these tasks I will create a single Stored Procedure to satisfy my requirements and I will access it in code behind according to the action performed by the end user on a button click. I have written this article specially focusing on newcomers and anyone new to SQL Stored Procedures so let us start with a basic introduction. What is Stored Procedure? A Stored Procedure is a group of logical SQL statements to perform a specific task such as insert, select, update and delete operations on a table and so on which is stored in a SQL database. Creating a Stored Procedure Before creating a Stored Procedure, we will create one table named employee in the SQL database which looks as in the following image. I have set the primary key on the id column for the Identy specification.

Now we have a table to perform these operations. Now let us start to create the Stored Procedure. The Stored Procedure is created using the keyword Create Procedure followed by the procedure name. Let us create the Stored Prcedure named EmpEntry as given below. create Procedure EmpEntry ( --variable declareations @Action Varchar (10), --to perform operation according to string passed to this varible such as Insert,update,delete,select @id int=null, --id to perform specific task @Fname Varchar (50)=null, -- for FirstName @MName Varchar (50)=null, -- for MName @Lname Varchar (50)=null -- for LastName ) -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------exec EmpEntry @Action='delete' ,@Fname='S',@MName='R',@Lname='M',@id='13' -added by vithal wadje on 18-10-2012 for Csharp contribution -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------as Begin SET NOCOUNT ON; If @Action='Insert' --used to insert records Begin Insert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname) End else if @Action='Select' --used to Select records Begin select *from employee end

else if @Action='Update' --used to update records Begin update employee set FirstName=@Fname,MName=@MName,LastName=@Lname where id=@id End Else If @Action='delete' --used to delete records Begin delete from employee where id=@id end End

In the above Stored Procedure throught comments I have clearly explained which block is used for which purpose, so I have briefly explained it again. I have used @Action variable and assigned the string to them and according to the parameter passed to the Stored Procedure the particular block will be executed because I have kept these blocks or conditions in nested If else if conditional statements. "The most important thing is that I have assigned null to each variable to avoid the effect on the parameter passed to the Stored Procedure because we are passing a different number of parameters but not the same number of parameters to the Stored Procedure to perform these tasks." After creating this Stored Procedure, now let us use it. To execute the Stored Procedure EmpEntry that we created we need to use the keyword exec followed by the procedure name and the parameter list. I have explained how to use it below. Inserting the Records into the Employee table that we created with the EmpEntry procedure; see: exec EmpEntry @Action='Insert' ,@Fname='vithal',@MName='G',@Lname='Wadje' After running this query the records will be inserted into the table employee. To see the records inserted into the table the run following query: select * from employee the output will be as shown in the following:

Their are two records you have seen because I have executed the procedure two times. Selecting Records From table

exec EmpEntry @Action='Select'

The output will be as follows:

Updating Records of table

exec EmpEntry @Action='Update' ,@Fname='Manish',@MName='Kapil',@Lname='Sawant',@id=2 After executing the above query the id number 2 record will be updated in the table. To see, run the query: select * from employee The output will be as shown in the following:

Deleting the Records from table

exec EmpEntry @Action='delete' ,@id=2 After executing the above query the id number 2 record will be deleted from the table. To see, run the query: select * from employee The output will be as shown in the following:

Note

In my next article I will explain how to use this Stored Procedure in an ASP.Net form in code behind on a button click. I hope this article is useful for all readers.

OOPS Features with C# OOPS Concepts : All languages to be considered as Object Oriented Programming languages, these need to be based on the conceptual framework called Object model. object model defines following Major Pillars :

Abstraction Encapsulation Inheritance and Polymorphism {c# does not support Multiple Inheritance directly(butc, but supports Multi-level Inheritance}

And Minor Pillars :


Strongly Typed Concurrency Persistence

Some facts about Constructors :


It does not have a return type, not even void It can be Private, Public & Static.

Some facts about Destructors :


It cannot be Overloaded It cannot be Inherited.

Method Overloading :

Methods with the same name but different signatures are said to be Overloaded Methods. Signature of a method is the data types of the parameters, number of parameters and the sequence in which they are passed to the function. Eg - public double findsquare(double number); & public double findsquare(int number).

Operator Overloading :

To define the meaning of operator, you have to define a function called as "Operator" function. this function is defined with "Operator: keyword and it defines the action of the operator relative to its classes. Eg - public static Complex operator+(Complex c1, Complex c2) Operator function must be Public and Static.

Access Modifiers :

Public Members : Available to all those who can see the Class. Private Members: Available Only to that class. Protected Members: Available to that Class and the one derived from it. Internal Members : Available throughout the namespace,but have to create an object. Protected Internal : (Protected Members) + (Internal Members).

Basic Rules : Public/private dont go with "internal" and "protected". So, no public internal string str="jjj"; Static Class features :

It is sealed i.e it cannot be Inherited. It cannot be instantiated. No instance Type Constructors. Will contain only Static Members and Functions. No need to instantiate, just use the Class Name (dot) Function name.

In Order to Emulate a Static behavior from a Non-Static Class do the following steps:

make it sealed i.e public sealed class Class name make the Constructor Private.

Static Functions:

A public Class can have Static Functions. It is declared with Public i.e public static void funct(); Static functions are used in situations where you want to share some Business Logic code over and over in your UI. Think of them as global functions. You dont have to create an instance to access the code thus reducing lot of overhead. Only Static data members are accessible inside static methods.

Static Constructor: A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only.

It can be used with Public Class. A static constructor does not take access modifiers or have parameters A Static Constructor cannot be called directly.

A Static Constructor is called to automatically initialize the class before the first instance is created or any static members are referenced.

Eg: link: http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx Structure in C#: It is basically used to encapsulate small groups of related variables Eg: struct point { public int x; public int y; }

Structures can have Constructor When you write Constructor for Structure it should be Parameterised CTOR. Cannot write default CTOR for Structure. Structure in .NET can also implement Interfaces (also multiple). By default Structures are sealed i.e They cannot be inherited. Also, they cannot inherit any other class.

Polymorphism ( Late Binding):


is achieved using "virtual' functions and Inheritance. "virtual" keyword is used to define a method in base class and "override" class in derived class is to extend base class behavior. an "Override" declaration cannot change the accessibility of the Virtual method. Both the 'override' and 'virtual' method must have the same access level modifier. "virtual" modifier cannot be used with static, abstract and override modifiers Not mandatory to override in base class.

Shadowing :

used to explicitly hide a member inherited from a base class. "new" modifier is used for this purpose. "new" and "override" cannot be used for the same member.

Usage : virtual(base class)/new(derived class) and public(base class)/new(derived class) , So it is not a replacement for override modifier but can be used for override as well.

Sealed :

Applicable not only to Class but also to methods. When applied to Class , The class cannot be Inherited. When applied to Method, the following conditions exist:

1. should always be used with override modifier. 2. Applying sealed to methods, is useful when classC inherits ClassB inherits ClassA and Class A has a virtual function named "Go()" which when overrided in class B as "sealed override Go()" cannot be further Overriden by class C as "override Go()".

Hence it is useful only for Multi-level inheritance.

Abstract Class :

cannot be Instantiated.but could be Inherited. must provide at least One Abstract Method. Only Abstract Class can have abstract Methods. Must be Overridden in derived class. Only Support Single Level Inheritance.

Interfaces:

Cannot be Instantiated. Usage-

interface IOrderDetails{void showdetails();} interface ICustDetails{void showdetails();} class Transaction : IOrderDetails,ICustDetails { void IOrderDetails..showdetails() { //implementation logic } void ICustDetails..showdetails() { //implementation logic }

static void Main() { Transaction obj = new Transaction(); IOrderDetails OD = obj; OD.ShowDetails(); ICustDetails CD = obj; CD.ShowDetails(); } }

Introduction to Object Oriented Programming Concepts (OOPS) in C#.net

OOPS Concepts
Class: It is a collection of objects. Object: It is a real time entity. An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address. In pure OOP terms an object is an instance of a class

The above template describe about object Student Class is composed of three things name, attributes, and operations public class student { } student objstudent=new student ();

According to the above sample we can say that Student object, named objstudent, has created out of the student class. In real world you will often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the Textbox control, you always used, is made out of the Textbox class, which defines its appearance and capabilities. Each time you drag a Textbox control, you are actually creating a new instance of the Textbox class.

Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit. Example for encapsulation is class. A class can contain data structures and methods. Consider the following class public class Aperture { public Aperture () { } protected double height; protected double width; protected double thickness; public double get volume() { Double volume=height * width * thickness; if (volume<0) return 0; return volume; } } In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier

Abstraction:
Abstraction is a process of hiding the implementation details and displaying the essential features. Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speakers works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal

details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone. So here the Laptop is an object that is designed to hide its complexity. How to abstract: - By using Access Specifiers

.Net has five access Specifiers


Public -- Accessible outside the class through object reference. Private -- Accessible inside the class only through member functions. Protected -- Just like private but Accessible in derived classes also through member functions. Internal -- Visible inside the assembly. Accessible through objects. Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions. Lets try to understand by a practical example:-

public class Class1 { int i; //No Access specifier means private public int j; // Public protected int k; //Protected data internal int m; // Internal means visible inside assembly protected internal int n; //inside assembly as well as to derived classes outside assembly static int x; // This is also private public static int y; //Static means shared across objects [DllImport("MyDll.dll")] public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly public void myFoo2() { //Within a class if you create an object of same class then you can access all data members through object reference even private data too Class1 obj = new Class1(); obj.i =10; //Error cant access private data through object.But here it is accessible.:) obj.j =10; obj.k=10; obj.m=10; obj.n=10; // obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10;

Now lets try to copy the same code inside Main method and try to compile [STAThread] static void Main() { //Access specifiers comes into picture only when you create object of class outside the class Class1 obj = new Class1(); // obj.i =10; //Error cant access private data through object. obj.j =10; // obj.k=10; //Error cant access protected data through object. obj.m=10; obj.n=10; // obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; //Error cant access private data outside class // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10; } What if Main is inside another assembly [STAThread] static void Main() { //Access specifiers comes into picture only when you create object of class outside the class Class1 obj = new Class1(); // obj.i =10; //Error cant access private data through object. obj.j =10; // obj.k=10; //Error cant access protected data through object. // obj.m=10; // Error cant access internal data outside assembly // obj.n=10; // Error cant access internal data outside assembly obj.s =10; //Errror Static data can be accessed by class names only Class1.x = 10; //Error cant access private data outside class // obj.y = 10; //Errror Static data can be accessed by class names only Class1.y = 10; } In object-oriented software, complexity is managed by using abstraction. Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details. //

Inheritance:
Inheritance is a process of deriving the new class from already existing class C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.

Using System; Public class BaseClass { Public BaseClass () { Console.WriteLine ("Base Class Constructor executed"); } Public void Write () { Console.WriteLine ("Write method in Base Class executed"); } } Public class ChildClass: BaseClass { Public ChildClass () { Console.WriteLine("Child Class Constructor executed"); } Public static void Main () { ChildClass CC = new ChildClass (); CC.Write (); }

In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass. The output of the above program is Output: Base Class Constructor executed Child Class Constructor executed Write method in Base Class executed this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes. In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name. Syntax: class ChildClassName: BaseClass { //Body }

C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time error: Class 'C' cannot have multiple base classes: 'A' and 'B'. public class A { } public class B { } public class C : A, B { } In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method(). Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article. Using System; Public class A { Public void A_Method () { Console.WriteLine ("Class A Method Called"); } } Public class B: A { Public void B_Method () { Console.WriteLine ("Class A Method Called"); } } Public class C: B { Public void C_Method () { Console.WriteLine ("Class A Method Called"); } Public static void Main () { C C1 = new C (); C1.A_Method (); C1.B_Method ();

C1.C_Method ();

} When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.

Common Interview Question: Are private class members inherited to the derived
class? Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error. Using System; Public class A { Public void M1 () { } Private void M2 () { } } Public class B: A { Public static void Main () { B B1 = new B (); B1.M1 (); //Error, Cannot access private member M2 //B1.M2 (); } } Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding. If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.

Using System; Public class Parent { Public void Write () {

} }

Console.WriteLine ("Parent Class write method");

Public class Child: Parent { Public new void Write () { Console.WriteLine ("Child Class write method"); } Public static void Main () { Child C1 = new Child (); C1.Write (); //Type caste C1 to be of type Parent and call Write () method ((Parent) C1).Write (); } }

Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms. Polymorphism is one of the fundamental concepts of OOP.

Polymorphism provides following features:


It allows you to invoke methods of derived class through base class reference during runtime. It has the ability for classes to provide different implementations of methods that are called through the same name.

Polymorphism is of two types:


1. Compile time polymorphism/Overloading 2. Runtime polymorphism/Overriding

Compile Time Polymorphism


Compile time polymorphism is method and operators overloading. It is also called early binding. In method overloading method performs the different task at the different input parameters.

Runtime Time Polymorphism

Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding. When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype. Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar. Method overloading has nothing to do with inheritance or virtual methods. Following are examples of methods having different overloads: void area(int side); void area(int l, int b); void area(float radius); Practical example of Method Overloading (Compile Time Polymorphism) using System; namespace method_overloading { class Program { public class Print { public void display(string name) { Console.WriteLine ("Your name is : " + name); } public void display(int age, float marks) { Console.WriteLine ("Your age is : " + age); Console.WriteLine ("Your marks are :" + marks); } } static void Main(string[] args) { Print obj = new Print (); obj.display ("George"); obj.display (34, 76.50f); Console.ReadLine ();

} } }

Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.

When and why to use method overloading Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task. You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing. Method overloading showing many forms. using System; namespace method_overloading_polymorphism { Class Program { Public class Shape { Public void Area (float r) { float a = (float)3.14 * r; // here we have used function overload with 1 parameter. Console.WriteLine ("Area of a circle: {0}",a); } Public void Area(float l, float b) { float x = (float)l* b; // here we have used function overload with 2 parameters. Console.WriteLine ("Area of a rectangle: {0}",x); } public void Area(float a, float b, float c) { float s = (float)(a*b*c)/2; // here we have used function overload with 3 parameters. Console.WriteLine ("Area of a circle: {0}", s); } } Static void Main (string[] args) { Shape ob = new Shape (); ob.Area(2.0f); ob.Area(20.0f,30.0f); ob.Area(2.0f,3.0f,4.0f); Console.ReadLine (); } } }

Things to keep in mind while method overloading If you use overload for method, there are couple of restrictions that the compiler imposes. The rule is that overloads must be different in their signature, which means the name and the number and type of parameters. There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.

Method Overriding:
Whereas Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords. Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword. Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called. Example: // Base class public class BaseClass { public virtual void Method1() { Console.Write("Base Class Method"); } } // Derived class public class DerivedClass : BaseClass { public override void Method1() { Console.Write("Derived Class Method"); } } // Using base and derived class public class Sample { public void TestMethod() { // calling the overriden method DerivedClass objDC = new DerivedClass(); objDC.Method1(); // calling the baesd class method BaseClass objBC = (BaseClass)objDC; objDC.Method1();

} } Output --------------------Derived Class Method Derived Class Method

Constructors and Destructors:


Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects. Constructors and destructors do not have return types nor can they return values. References and pointers cannot be used on constructors and destructors because their addresses cannot be taken. Constructors cannot be declared with the keyword virtual. Constructors and destructors cannot be declared const, or volatile. Unions cannot contain class objects that have constructors or destructors.

Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects. The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator. Example of Constructor class C { private int x; private int y; public C (int i, int j) { x = i; y = j; } public void display () { Console.WriteLine(x + "i+" + y); }

} Example of Destructor class D { public D () { // constructor } ~D () { // Destructor } }

Basic Concepts of OOPs in .Net with C# and VB.Net


Introduction .NET is fully object oriented platform that allow languages to take full advantage of these OO features. The features include: Namespace Classes Abstract Encapsulation Overloading New. Overriding Interfaces Polymorphism Lets take a quick look at what each of this term means. Namespace Even though namespace is not really an OOPs feature, .NET use it extensively. Namespace is nothing but a logical container for various classes. Under given namespace class names must be unique. Namespace server two purposes they provide logical organization of classes and they also avoid ambiguity. Classes Class is nothing but a template or blue-print for an entity. For example you may have a class that represents real life entity Employee. The class will provide properties (Name, Age) as well as actions (CalculateSalary, GoOnLeave) of the entity. Objects Instances of classes are called as objects. For example there might be three instances of the Employee class mentioned above. They might represent individual employees John, Bob and Tom. Encapsulation Each object typically deals with some kind of data or the other. Not all the data needs to be exposed to external systems. This can be controlled via data encapsulation. Overloading Overloading refers to the methods or functions having same name but varying parameters. The parameters should vary with respect to data types and order. If no modifier is specified, the method is given private access. Inheritance

Inheritance refers to extending functionality of existing class. Inheritance is useful when developing "object models" for your system. .NET supports only single inheritance. Overriding Overriding refers to the methods in the child class having the same signature (name as well as parameters) as of the parent class methods. Interfaces Interfaces are nothing but models of class properties and methods without any implementation. The class implements the interface. Once a class implements any interface it must implement all the properties and methods (although the implementation can be empty or null implementation). Polymorphism Polymorphism refers to the ability of the system to call correct implementation of methods with the same name. For example, Clerk as well as Manager class might have a method called CalculateSalary(). However, at runtime depending on whether the underlying object is of type Clerk or Manager correct version of the method is called. Creating namespaces Namespaces are created using keyword Namespace (namespace in C#). Following example shows how to declare a namespace. [VB.NET] Namespace MyNamespace End Namespace [C#] namespace MyNamespace {} Note that one assembly can have one or more namespaces. Also, one namespace can span across multiple assemblies. You can create nested namespaces as follows: [VB.NET] Namespace MyNamespace Namespace MuSubNamespace End Namespace End Namespace [C#] namespace MyNamespace { namespace MySubNamespace { } } If you are using VS.NET then the project name acts as the default namespace name. Creating classes Creating classes is similar to creating namespaces.

[VB.NET] Public Class Class1 End Class [C#] public class Class1 { } Generally classes will be part of some of the namespace. Creating Properties Properties encapsulate data members of your class. Properties can be read-write, read only or write only. Here is how you create read-write properties: [VB.NET] Public Class Employee private strName As String Public Property Name As String Get return strName; End Get Set(value As String) strName=value; End Set End Property End Class [C#] public class Class1 { public string Name { string strName; get { return strName; } set { strName=value; } } } Here, VB.NET uses Property keyword to declare properties. C# does not have this keyword Property definition consists of two parts Get and Set. The get part returns the property value and set par sets some private variable. The value in Set routine is received via implicit variable called value in C#. VB.NET allows you to change this. Creating methods Methods represent actions performed by the object. In VB.NET functions and sub routines are collectively called as methods. In C# everything is function. [VB.NET] Public Sub CalculateSalary()

End Sub [C#] public void CalculateSalary() { } Method overloading Method overloading refers to methods with same name but different types or order of parameters. Following example make it clear: [VB.NET] Public Sub CalculateSalary() End Sub Public Sub CalculateSalary(month as Integer) End Sub [C#] public void CalculateSalary() { } public void CalculateSalary(int month) { } In VB.NET you can also use optional parameters to achieve similar functionality. However, it is recommended to use overloading instead to make your code consistent across languages. Inheritance Inheritance is the ability to extend existing class further. Unlike languages like C++ that allow multiple inheritance .NET allows only single inheritance. This means that at a time you can inherit from a single class. [VB.NET] Public Class Manager Inherits Employee End Class [C#] public class Manager : Employee { } In the above example, we create a class called Manager that inherits from Employee class. As you can guess Manager is specific implementation of generic

Employee class. VB.NET uses Inherits keyword to indicate the parent class where as C# uses : operator to indicate that. Method Overriding In order to override method in child class they need to be marked as Overridable (VB.NET) or virtual (C#) in the parent class. [VB.NET] Public Overridable Function CalculateSalary() As Integer End Function [C#] public virtual int CalculateSalary() { } Then in the child class you can create a method with the same signature and specify that it overrides the base class method. [VB.NET] Public Overrides Function CalculateSalary() As Integer End Function [C#] public override int CalculateSalary() { } Note that if you do not provide the Overrides (VB.NET) or override (C#) keywords in the child class the compiler issues a warning that you are hiding a base class member. In this case you can either put the above keywords or use Shadows (VB.NET) or new (C#) keywords. Using these keywords ,however, will hide the base class members. Creating Interfaces Just like classes are templates for real life entities, interfaces can be thought of as templates for classes. They bring uniformity in your object model. [VB.NET] Public Interface IEmployee Property EmployeeID() As Integer Property Name() As String Property Age() As Integer Function CalculateSalary() As Integer End Interface [C#] public interface IEmployee {

int EmployeeID { get; } string Name { get; set; } int Age { get; set; } int CalculateSalary(); } As you can see VB.NET uses Interface keyword to define an interface. Similarly, C# uses interface keyword. Note, how they contain only property and method signatures and no code at all. Implementing Interfaces The main difference between inheritance based programming and interfaces based programming is that interfaces just specify signatures of properties and methods for a class. Your class "implements" the interface by providing implementation for various properties and methods. Unlike inheritance there is no "code" inherited from interfaces. Your class can implement one or more interfaces. [VB.NET] Public Class Manager Implements IEmployee Public Function CalculateSalary() As Integer Implements IEmployee.CalculateSalary End Function End Class [C#] public class Manager : IEmployee { public int CalculateSalary() { } } Above example shows how VB.NET uses Implements keyword to implement an interface. Note how VB.NET also requires the use of Implements keyword for each property and method. You must have guessed from this that in VB.NET you can give different name to the implemented member than the interface. This feature is not

available in C#. C# do not have a special keyword and uses the same : operator to implement the interface. Polymorphism Consider following lines of code: [VB.NET] Dim emp As Employee emp = New Clerk() Console.WriteLine ("Clerk Salary :{0}", emp.CalculateSalary()) emp = New Manager() Console.WriteLine ("Manager Salary :{0}", emp.CalculateSalary()) [C#] Employee emp; emp=new Clerk(); Console.WriteLine ("Clerk Salary :{0}",emp.CalculateSalary()); emp=new Manager(); Console.WriteLine ("Manager Salary :{0}",emp.CalculateSalary()); Here, we have declared a variable of type Employee. A variable of parent class type can point to instance of any of its children. First, we point it to an instance of Clerk class. Then we point it to an instance of Manager class. Even though the variable is of type Employee, depending on which child type it is pointing to it calls the correct implementation of CalculateSalary() method. The underlying system does this via inheritance polymorphism. Similar thing can also be achieved in interface polymorphism. [VB.NET] Dim emp As IEmployee emp = New Clerk() Console.WriteLine ("Clerk Salary :{0}", emp.CalculateSalary()) emp = New Manager() Console.WriteLine ("Manager Salary :{0}", emp.CalculateSalary()) [C#] IEmployee emp; emp=new Clerk(); Console.WriteLine ("Clerk Salary :{0}",emp.CalculateSalary()); emp=new Manager(); Console.WriteLine ("Manager Salary :{0}",emp.CalculateSalary()); OOPs Interview Questions Class A user-defined data structure that groups properties and methods. Class doesnt occupies memory.

Object
Instance of Class is called object. An object is created in memory using keyword new.

Difference between Struct and Class


Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap. Struct do not support inheritance, while class supports inheritance. However struct can implements interface. Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

What is the difference between instantiating structures with and without using the new keyword? When a structure is instantiated using the new keyword, a constructor (noargument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.

Encapsulation
Wrapping up of data and function into a single unit is known as Encapsulation.

Properties
Attribute of object is called properties. Eg1:- A car has color as property. Eg2: private
string m_Color;;

public string Color { get

{ return m_Color; } set { m_Color = value; } }

Car Maruti = new Car(); Maruti.Color= White; Console.Write(Maruti.Color);


Isn't it better to make a field public than providing its property with both set { } and get { } block? After all the property will allow the user to both read and modify the field so why not use public field instead? Motivate your answer Not always! Properties are not just to provide access to the fields; rather, they are supposed to provide controlled access to the fields of our class. As the state of the class depends upon the values of its fields, using properties we can assure that no invalid (or unacceptable) value is assigned to the fields. Eg:

private int age; public int Age { get { return age; } set { if(value <> 100)

//throw exception else age = value; } }

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

Eg2: class Circle { double x,y,radius; Circle(double x){ this(x,0,1); } Circle(double x, double y){ this(x,y,1); } Circle(double x, double y, double radius){ this.x = x; this.y = y; this.radius = radius; } }

Constructor

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

Static Members of the class Static members belong to the whole class rather than to individual object Static members are accessed with the name of class rather than reference to objects. Eg: class Test { public int rollNo; public int mathsMarks; public static int totalMathMarks; }

class TestDemo { public static void main() { Test stud1 = new Test(); stud1.rollNo = 1; stud1.mathsMarks = 40; stud2.rollNo = 2; stud2.mathsMarks = 43; Test.totalMathsMarks = stud1.mathsMarks + stud2.mathsMarks;

}
}
Static Method of the class

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

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

Protected override void Finalize() { try { Console.WriteLine(Destructing Object.); //put some code here. } finally { base.Finalize(); } }

Destructor
A destructor is just opposite to constructor. It has same as the class name, but with prefix ~ (tilde). They do not have return types, not even void and therefore they cannot return values. destructor is invoked whenever an object is about to be garbage collected Eg: class person { //constructor person()

{ } //destructor ~person() { //put resource freeing code here. } } What is the difference between the destructor and the Finalize() method? When does the Finalize() method get called? Finalize() corresponds to the .Net Framework and is part of the System.Object class. Destructors are C#'s implementation of the Finalize() method. The functionality of both Finalize() and the destructor is the same, i.e., they contain code for freeing the resources when the object is about to be garbage collected. In C#, destructors are converted to the Finalize() method when the program is compiled. The Finalize() method is called by the .Net Runtime and we can not predict when it will be called. It is guaranteed to be called when there is no reference pointing to the object and the object is about to be garbage collected.

Garbage Collection

Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable. .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect(). Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.

Enumeration
Enumeration improves code readability. It also helps in avoiding typing mistake.

Concept of Heap and Stack


Local Variables
Free Memory Heap (Larger Memory Area than Stack). Global Variables Program Instruction Permanent Storage area Stack

The Program Instruction and Global and Static variables are stored in a region known as permanent storage area and the local variables are stored in another area called stack. The memory space located between these two regions is available for dynamic memory allocation during execution of program. This free memory region is called heap. The size of heap keeps on changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore, it is possible to encounter memory overflow during dynamic allocation process.

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

Value Type
As name suggest Value Type stores value directly. For eg: //I and J are both of type int I = 20; J = I;

int is a value type, which means that the above statements will results in two locations in memory. For each instance of value type separate memory is allocated. Stored in a Stack. It Provides Quick Access, because of value located on stack.

Reference Type
As name suggest Reference Type stores reference to the value. For eg: Vector X, Y; //Object is defined. (No memory is allocated.) X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.) X.value = 30; //Initialising value field in a vector class. Y = X; //Both X and Y points to same memory location. //No memory is created for Y. Console.writeline(Y.value); //displays 30, as both points to same memory Y.value = 50; Console.writeline(X.value); //displays 50. Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null; Reference type are stored on Heap. It provides comparatively slower access, as value located on heap. ref keyword Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable must be initialized before it is passed into a method.

out keyword out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. It is useful when we want to return more than one value from the method.

Note: You must assigned value to out parameter in method body, otherwise the method wont compiled.

Boxing and Un-Boxing


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

Inheritance
The process of sub-classing a class to extend its functionality is called Inheritance. It provides idea of reusability.

Order of Constructor execution in Inheritance


constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy.

Order of Destructor execution in Inheritance


The destructors are called in the reverse order, i.e., from the bottom to the top (child to parent class) in the inheritance hierarchy.
What are Sealed Classes in C#? The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class) Can you prevent your class from being inherited by another class? Yes. The keyword sealed will prevent the class from being inherited.

Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.

Fast Facts of Inheritance


Multiple inheritance of classes is not allowed in C#. In C# you can implements more than one interface, thus multiple inheritance is achieved through interface. The Object class defined in the System namespace is implicitly the ultimate base class of all the classes in C# (and the .NET framework) Structures (struct) in C# does not support inheritance, it can only implements interfaces.

Polymorphism
Polymorphism means same operation may behave differently on different classes. Eg: Method Overloading is an example of Compile Time Polymorphism. Method Overriding is an example of Run Time Polymorphism Does C#.net supports multiple inheritance?

No. A class can inherit from only one base class, however a class can implements many interface, which servers some of the same purpose without increasing complexity. How many types of Access Modifiers. 1) Public Allows the members to be globally accessible. 2) Private Limits the members access to only the containing type. 3) Protected Limits the members access to the containing type and all classes derived from the containing type. 4) Internal Limits the members access to within the current project.

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

Method Overriding
Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.

Method overriding forms Run-time polymorphism. Note: By default functions are not virtual in C# and so you need to write virtual explicitly. While by default in Java each function are virtual. Eg1: Class parent { virtual void hello() { Console.WriteLine(Hello from Parent); } } Class child : parent { override void hello() { Console.WriteLine(Hello from Child); } } static void main() { parent objParent = new child(); objParent.hello(); } //Output Hello from Child.

Virtual Method

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

What is Interface

An Interface is a group of constants and method declaration. .Net supports multiple inheritance through Interface.

Interface states what to do, rather than how to do. An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class. It is possible, therefore, for different objects to provide dramatically different implementations of the same members. Example1, the Car object might implement the IDrivable interface (by convention, interfaces usually begin with I), which specifies the GoForward, GoBackward, and Halt methods. Other classes, such as Truck, Aircraft, Train or Boat might implement this interface and thus are able to interact with the Driver object. The Driver object is unaware of which interface implementation it is interacting with; it is only aware of the interface itself. Example2, an interface named IShape, which defines a single method CalculateArea. A Circle class implementing this interface will calculate its area differently than a Square class implementing the same interface. However, an object that needs to interact with an IShape can call the CalculateArea method in either a Circle or a Square and obtain a valid result. Practical Example

public interface IDrivable { void GoForward(int Speed); } public class Truck : IDrivable { public void GoForward(int Speed) { // Implementation omitted } } public class Aircraft : IDrivable { public void GoForward(int Speed) { // Implementation omitted } } public class Train : IDrivable { public void GoForward(int Speed) { // Implementation omitted

} }

Extra

Each variable declared in interface must be assigned a constant value. Every interface variable is implicitly public, static and final. Every interface method is implicitly public and abstract. Interfaces are allowed to extends other interfaces, but sub interface cannot define the methods declared in the super interface, as sub interface is still interface and not class. If a class that implements an interface does not implements all the methods of the interface, then the class becomes an abstract class and cannot be instantiated. Both classes and structures can implement interfaces, including multiple interfaces.

Making choice between Interface and Abstract Class


In which Scenario you will go for Interface or Abstract Class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without br

Difference between Interface and Abstract Class Interfaces vs. Abstract Classes
Feature Multiple inheritance Interface Abstract class extend only one A class may implementA class may several interfaces. abstract class.

An abstract class can provide An interface cannot provide Default complete code, default code, any code at all, much less implementation and/or just stubs that have to be default code. overridden. Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.

since the qualification is optional. Third party convenience An interface implementation A third party class must be may be added to any rewritten to extend only from the existing third party class. abstract class. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.

Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Is-a vs -able or Automobile class might can-do implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

Plug-in

You must use the abstract class asis for the code base, with all its attendant baggage, good or bad. The abstract class author has You can write a new imposed structure on you. replacement module for an Depending on the cleverness of the interface that contains not author of the abstract class, this one stick of code in common may be good or bad. Another issue with the existing that's important is what I call implementations. When you "heterogeneous vs. homogeneous." implement the interface, you If implementors/subclasses are start from scratch without homogeneous, tend towards an any default implementation. abstract base class. If they are You have to obtain your heterogeneous, use an interface. tools from other classes; (Now all I have to do is come up nothing comes with the with a good definition of interface other than a few hetero/homogeneous in this constants. This gives you context.) If the various objects are freedom to implement a all of-a-kind, and share a common radically different internal state and behavior, then tend design. towards a common base class. If all they share is a set of method signatures, then tend towards an interface. If all the various If the various implementations are implementations share is the all of a kind and share a common method signatures, then an status and behavior, usually an interface works best. abstract class works best. If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.

Homogeneity

Maintenance

Speed

Slow, requires extra indirection to find the corresponding method in the Fast actual class. Modern JVMs are discovering ways to reduce this speed penalty. The constant declarations in You can put shared code into an an interface are all presumed abstract class, where you cannot

Terseness

into an interface. If interfaces want public static final, so you to share code, you will have to may leave that part out. You write other bubblegum to arrange can't call any methods to that. You may use methods to compute the initial values of compute the initial values of your your constants. You need not constants and variables, both declare individual methods of instance and static. You must an interface abstract. They declare all the individual methods are all presumed so. of an abstract class abstract. If you add a new method to If you add a new method to an an interface, you must track abstract class, you have the option down all implementations of of providing a default that interface in the universe implementation of it. Then all and provide them with a existing code will continue to work concrete implementation of without change. that method.

Adding functionality

Difference between Object Base and Object Oriented ?


In object oriented you use build in class, template class and also define your own class but in object base we can only use build in class User cannot create his own class.

What are the OOPS concepts?


1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data.

2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors.

3) Polymorphism: It is a feature that allows one interface to be used for

general class of actions. The specific action is determined by the exact nature of the situation. In general polymorphism means "one interface, multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. OOPS Concepts OOPS Features : The object oriented programming (OOP) is a programming model where Programs are organized around object and data rather than action and logic. * OOP allow decomposition of a problem into a number of entities called Object and then builds data and function around these objects. The Program is divided into number of small units called Object. The data and function are build around these objects. The data of the objects can be accessed only by the functions associated with that object. The functions of one object can access the functions of other object. What is Object? Objects are the basic run-time entities in an object oriented system.They may represent a person,a place or any item that the program has to handle. "Object is a Software bundle of related variable and methods. " Object is an instance of a class Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area. When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object. class Employee { } Syntax to create an object of class Employee:-

Employee objEmp = new Employee(); What is Class? A class is the core of any modern Object Oriented Programming language such as C#. In OOP languages it is must to create a class for representing data.Class is a blueprint of an object that contains variables for storing data and functions to performing operations on these data. Class will not occupy any memory space and hence it is only logical representation of data.To create a class, you simply use the keyword "class" followed by the class name: class Employee { } Difference between a Class and an object Posted by: Ddd Class: 1)It is a datatype that contains the programming logic. 2)Class is visible in the source code and resides in hard disk. 3)Class is like a template or blueprint of the object. It implements reusability, encapsulation, inheritance example:Button is a class with properties like Text,BackColor, events like click, methods like Focus Object: 1)it is a chunk of memory that implements the class logic. 2)Object is in the RAM and not visible in source code. 3)It is the real world implementation of the class. Each object has its own copy of data. example: Button1, Button2 are the objects of Button class. Value Type As name suggest Value Type stores value directly. For eg: //I and J are both of type int I = 20;

J = I; int is a value type, which means that the above statements will results in two locations in memory. For each instance of value type separate memory is allocated. Stored in a Stack. It Provides Quick Access, because of value located on stack. Reference Type As name suggest Reference Type stores reference to the value. For eg: Vector X, Y; //Object is defined. (No memory is allocated.) X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.) X.value = 30; //Initialising value field in a vector class. Y = X; //Both X and Y points to same memory location. //No memory is created for Y. Console.writeline(Y.value); //displays 30, as both points to same memory Y.value = 50; Console.writeline(X.value); //displays 50. Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null; Reference type are stored on Heap. It provides comparatively slower access, as value located on heap. ref keyword Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable must be initialized before it is passed into a method. out keyword out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. It is useful when we want to return more than one value from the method. Note: You must assigned value to out parameter in method body, otherwise the method wont compiled. Boxing and Un-Boxing Boxing: means converting value-type to reference-type. Eg: int I = 20; string s = I.ToSting(); UnBoxing: means converting reference-type to value-type. Eg: int I = 20; string s = I.ToString(); //Box the int int J = Convert.ToInt32(s); //UnBox it back to an int. Note: Performance Overheads due to boxing and unboxing as the boxing makes a copy of value type from stack and place it inside an object of type System.Object in

the heap. What is Static field? To indicate that a field should only be stored once no matter how many instance of the class we create. What is Static Method? It is possible to declare a method as Static provided that they don't attempt to access any instance data or other instance methods. What is Virtual keyword? This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events. The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class. What is Polymorphisms? Polymorphism means one name many forms. One function behaves different forms. In other words, "Many forms of a single object is called Polymorphism." Real World Example of Polymorphism: Example-1: A Teacher behaves to student. A Teacher behaves to his/her seniors. Here teacher is an object but attitude is different in different situation. Example-2: Person behaves SON in house at the same time that person behaves EMPLOYEE in office. Example-3: Your mobile phone, one name but many forms As phone As camera As mp3 player As radio Example of Compile Time Polymorphism: Method Overloading Example of Run Time Polymorphism: Method Overriding Example of Compile Time Polymorphism Method Overloading - Method with same name but with different arguments is called method overloading. - Method Overloading forms compile-time polymorphism. - Example of Method Overloading: class A1

{ void hello() { Console.WriteLine(Hello); } void hello(string s) { Console.WriteLine(Hello {0},s); } }

Example of Run Time Polymorphism Method Overriding - Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass. - Method overriding forms Run-time polymorphism. - Note: By default functions are not virtual in C# and so you need to write virtual explicitly. While by default in Java each function are virtual. - Example of Method Overriding: Class parent { virtual void hello() { Console.WriteLine(Hello from Parent); } } Class child : parent { override void hello() { Console.WriteLine(Hello from Child); } } static void main() { parent objParent = new child(); objParent.hello(); } //Output Hello from Child. What is Inheritance? When a class acquire the property of another class is known as inheritance. Inheritance is process of object reusability. For example, A Child acquire property of Parents. public class ParentClass {

public ParentClass() { Console.WriteLine("Parent Constructor."); } public void print() { Console.WriteLine("I'm a Parent Class."); } } public class ChildClass : ParentClass { public ChildClass() { Console.WriteLine("Child Constructor."); } public static void Main() { ChildClass child = new ChildClass(); child.print(); } } Output: Parent Constructor. Child Constructor. I'm a Parent Class. Abstraction: Abstraction is "To represent the essential feature without representing the back ground details." Abstraction lets you focus on what the object does instead of how it does it. Abstraction provides you a generalized view of your classes or object by providing relevant information. Abstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner. Real world Example of Abstraction: Suppose you have an object Mobile Phone.

Suppose you have 3 mobile phones as following:Nokia 1400 (Features:- Calling, SMS) Nokia 2700 (Features:- Calling, SMS, FM Radio, MP3, Camera) Black Berry (Features:-Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails) Abstract information (Necessary and Common Information) for the object "Mobile Phone" is make a call to any number and can send SMS." so that, for mobile phone object you will have abstract class like following:abstract class MobilePhone { public void Calling(); public void SendSMS(); } public class Nokia1400 : MobilePhone { } public class Nokia2700 : MobilePhone { public void FMRadio(); public void MP3(); public void Camera(); } public class BlackBerry : MobilePhone { public void FMRadio(); public void MP3(); public void Camera(); public void Recording(); public void ReadAndSendEmails(); } Abstraction means putting all the variables and methods in a class which are necessary. For example: - Abstract class and abstract method.

Abstraction is the common thing. example: If somebody in your collage tell you to fill application form, you will fill your details like name, address, data of birth, which semester, percentage you have got etc. If some doctor gives you an application to fill the details, you will fill the details like name, address, date of birth, blood group, height and weight. See in the above example what is the common thing? Age, name, address so you can create the class which consist of common thing that is called abstract class. That class is not complete and it can inherit by other class. Encapsulation: Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation. Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object. Encapsulation is like your bag in which you can keep your pen, book etc. It means this is the property of encapsulating members and functions. class Bag { book; pen; ReadBook(); }

Encapsulation means hiding the internal details of an object, i.e. how an object does something. Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented. Encapsulation is a technique used to protect the information in an object from the other object. Hide the data for security such as making the variables as private, and expose the property to access the private data which would be public. So, when you access the property you can validate the data and set it. Example:

class Demo { private int _mark; public int Mark { get { return _mark; } set { if (_mark > 0) _mark = value; else _mark = 0; } } } Real world Example of Encapsulation:Let's take example of Mobile Phone and Mobile Phone Manufacturer Suppose you are a Mobile Phone Manufacturer and you designed and developed a Mobile Phone design(class), now by using machinery you are manufacturing a Mobile Phone(object) for selling, when you sell your Mobile Phone the user only learn how to use the Mobile Phone but not that how this Mobile Phone works. This means that you are creating the class with function and by making object (capsule) of it you are making availability of the functionality of you class by that object and without the interference in the original class. Example-2: TV operation It is encapsulated with cover and we can operate with remote and no need to open TV and change the channel. Here everything is in private except remote so that anyone can access not to operate and change the things in TV. Difference between Abstraction and Encapsulation :Abstraction Encapsulation 1. Abstraction solves the problem in the design level. 1. Encapsulation solves the problem in the implementation level. 2. Abstraction is used for hiding the unwanted data and giving relevant data. 2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.

3. Abstraction lets you focus on what the object does instead of how it does it

3. Encapsulation means hiding the internal details or mechanics of how an object does something. 4. Abstraction- Outer layout, used in terms of design. For Example:Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number. 4. Encapsulation- Inner layout, used in terms of implementation. For Example:- Inner Implementation detail of a Mobile Phone, how keypad button and Display Screen are connect with each other using circuits.

What is Abstract Class? Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited. There are scenarios in which it is useful to define classes that is not intended to instantiate; because such classes normally are used as base-classes in inheritance hierarchies, we call such classes abstract classes. Abstract classes cannot be used to instantiate objects; because abstract classes are incomplete, it may contain only definition of the properties or methods and derived classes that inherit this implements it's properties or methods. Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract. What is an Interface? An interface is a contract & defines the requisite behavior of generalization of types. An interface mandates a set of behavior, but not the implementation. Interface must be inherited. We can't create an instance of an interface. An interface is an array of related function that must be implemented in derived type. Members of an interface are implicitly public & abstract. An interface can inherit from another interface. Interfaces Vs Abstract Class. A class may implement one or more interfaces. A class may inherit only one Abstract Class or any other class An interface cannot have access modifiers for any types declared in it. By Default all are public. An abstract class can contain access modifiers. If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

Requires more time to find the actual method in the corresponding classes. Fast All methods declared in interface must be implemented in derived class. Only abstract methods need to be implemented in derived classes. If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code will work without any modification. No fields can be defined in interfaces We can define fields and constants in abstract class. What is pure virtual function? When you define only function prototype in a base class without and do the complete implementation in derived class. This base class is called abstract class and client wont able to instantiate an object using this base class. A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0" syntax: class Base { public: void f1(); // not virtual virtual void f2(); // virtual, not pure virtual void f3() = 0; // pure virtual }; What is access modifier in C#? Access modifiers are keywords used to specify the declared accessibility of a member or a type. This section introduces the four access modifiers: public protected internal private public The type or member can be accessed by any other code in the same assembly or another assembly that references it. Example In the following example, two classes are declared, MyClass1 and MyClass2. The public members x and y of the MyClass1 are accessed directly from MyClass2. // protected_public.cs // Public access

using System; class MyClass1 { public int x; public int y; } class MyClass2 { public static void Main() { MyClass1 mC = new MyClass1(); // Direct access to public members: mC.x = 10; mC.y = 15; Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); } } private The type or member can be accessed only by code in the same class or struct. In this example, the Employee class contains a public member, Name, and a private member, Salary. The public member can be accessed directly, while the private member must be accessed through the public method AccessSalary(). // private_keyword.cs using System; class Employee { public string name = "xx"; double salary = 100.00; // private access by default public double AccessSalary() { return salary; } } class MainClass { public static void Main() { Employee e = new Employee(); // Accessing the public field: string n = e.name;

// Accessing the private field: double s = e.AccessSalary(); } } protected The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type. For example, consider the following code segment: class A { protected int x = 123; } class B : A { void F() { A a = new A(); B b = new B(); a.x = 10; // Error b.x = 10; // OK } } internal The type or member can be accessed by any code in the same assembly, but not from another assembly. Example This example contains two files, Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to access the member of the base class will produce an error. File Assembly1.cs: // Assembly1.cs // compile with: /target:library internal class BaseClass { public static int IntM = 0; } File Assembly2.cs // Assembly2.cs // compile with: /reference:Assembly1.dll // CS0122 expected class TestAccess

{ public static void Main() { BaseClass myBase = new BaseClass(); // error, BaseClass not visible outside assembly } } protected internal The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type. Default Access modifiers in C#? An enum has default modifier as public A class has default modifiers as Internal . It can declare members (methods etc) with following access modifiers: public internal private protected internal An interface has default modifier as public A struct has default modifier as Internal and it can declare its members (methods etc) with following access modifiers: public internal private A methods, fields, and properties has default access modifier as "Private" if no modifier is specified. What are Constructors ? Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization. If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor. A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures. Constructors do not return a value

Constructors can be overloaded Example: public class mySampleClass { public mySampleClass() { // This is the constructor method. } // rest of the class members goes here. } When the object of this class is instantiated, this constructor will be executed. Something like this: mySampleClass obj = new mySampleClass() // At this time the code in the constructor will // be executed What are the various types of Constructors Public : Accessible to All Private: Those classes in which only static members are there and you don't want there objects to be created in any class. Static: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers. Intern: implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly (Namespace). and External What is a private constructor? Where will you use it? When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern. If you declare a Constructor as private then it doesnt allow to create object for its derived class, i.e you loose inherent facility for that class. Example: Class A { // some code Private Void A() { //Private Constructor } } Class B:A

{ //code } B obj = new B();// will give Compilation Error Because Class A constructor declared as private hence its accessibility limit is to that class only, Class B can't access. When we create an object for Class B that constructor will call constructor A but class B have no rights to access the Class A constructor hence we will get compilation error. Differences between a structure and class Structure: 1)It is a Value Type 2)Its variable directly contains the data on the stack 3)Each structure variable has its independent copy of data. 4)One structure cannot inherit other 5)They do not have destructors 6)They do no have explicit parameterless constructors 7)we cannot put sealed /abstract modifiers before the structures. 8)Easier memory management 9)examples: int, short,long,DateTime, Point (predefined) Uses: Structures are typically used for handling small amounts of data or where inheritance, overriding is not required example: int a=100; Class 1)It is a reference Type 2)Its variable has references to the data(data is stored in the object created in the heap) . 3)Two Class variables can refer to the same object 4)One class can inherit the other(unless the class is sealed/static) 5)Classes have destructors 6)They can have explicit parameterless constructors 7)Sealed/abstract modifers can be put before classes. 8) Comparitively Difficult memory management 9)example: SqlConnection,DataView(predefined classes)

Classes are typically used where inheritance, overriding is required or we need to create objects capable of handling large data example: DataSet,ArrayList can handle large data. how to pass the values across webforms without using State Management Concepts:

Page1.aspx.cs public String CurrentCity { get { return TextBox1.Text; } }

In Page2.aspx <%@ PreviousPageType VirtualPath="~/Page1.aspx" %> Label1.Text=PreviousPage.CurrentCity;

Another Method: In Page2.aspx TextBox SourceTextBox = (TextBox)PreviousPage.FindControl("TextBox1"); Label1.Text = SourceTextBox.Text; OOPS Concept in C# Object Oriented Programming language(OOPS):- It is a methodology to write the program where we specify the code in form of classes and objects. CLASS:-Class is a user defined data type. it is like a template. In c# variable are termed as instances of classes. which are the actual objects. EX:Class classname { [variable declaration;]

[Method declaration;] } Here Class is a keyword and classname is valid c# identifier. Everything inside the square brackets is optional.It is also valid class definition. EX:Class Empty { } NOTE:- There are some similarities and difference between class & struct. we will discuss later. OBJECT:- Object is run time entity which has different attribute to identify it uniquely. EX:Here This is an example of creating an object of type Rectangle. Rectangle rect1=new rectangle(); Rectangle rect1=new rectangle(); Here variable 'rect1' & rect2 is object of the rectangle class. The Method Rectangle() is the default constructor of the class. we can create any number of objects of Rectangle class. Basic Principle of oops:- There are main three core principles of any object oriented languages.

ENCAPSULATION:- Encapsulation provides the ability to hide the internal details of an object from its users.The concept of encapsulation is also known as data hiding or information hiding. In c# , Encapsulation is implemented using the access modifier keywords. Public Private protected Internal Protected Internal

1. 2. 3. 4. 5.

POLYMORPHISM:- It is also concept of oops. It is ability to take more than one form. An operation may exhibit different behaviour in different situations. EX:- An addition operation involving

two numeric values will produce sum and the same addition operation will produce a string.If we pass parameter numeric value then method return sum(numeric value) and if we pass parameter String then same method is return string value .this called Polymorphish.

INHERITANCE:- One class can include the feature of another class by using the concept of inheritance.In c# a class can be inherit only from one class at a time.Whenever we create class that automatic inherit from System.Object class,till the time the class is not inherited from any other class.

EX:using System; namespace Inheritance { class Program { public static void Main() { employee obj2 = new employee(); obj2.display(); obj2.show(); Console.ReadLine(); } } public class cls { public void display() { Console.WriteLine("HELLO"); } } public class employee : cls { public void show() { Console.WriteLine("welcome"); } } }

NOTE:-Here we are calling cls class(base class) member by creating the object of employ class(child class).it is known as inheritance.

Re: Differences between VB.Net and C#, related to OOPS concepts Answer #1

c# is faster than vb.net C# can access unmanaged code in the background c# has more functionality
Is This Answer Correct ?

26 Yes

21 No

K L Baiju Re: Differences between VB.Net and C#, related to OOPS concepts Answer #2

vb.net is partially oops,were c# is full oops ... multiple multilevel is not possible in vb.net...in c# its available.
Is This Answer Correct ?

16 Yes

20 No

0 Vinod

Re: Differences between VB.Net and C#, related to OOPS concepts Answer #3

Multiple Inheritance is not possible in VB.NET, you have to use Interface to achieve this. In C# multiple inheritance is available. As every code is compiled to byte code in MSIL, it does not make a difference is execution speed. OOPs is added to VB.NET, whereas C# has it as part of it. VB.NET is easy to learn, C# is easy to write !! choice is yours!
Is This Answer Correct ?

7 Yes

22 No

0 Satish V Itagi Re: Differences between VB.Net and C#, related to OOPS concepts Answer #4

VB.NET & C# both have same execution speed no difference in terms of speed. But there are some other differrence between them:1- C# uses function pointers, VB.Net does not. 2- we can do operator overloading in C#, but not in VB.Net.

3- VB.Net uses WITH KEYWORD, C# does not have WITH Keyword (Example:- WITH datagrid .datasource=ds .databind() END WITH) 4- C# is case senstive language, but VB.Net is not. 5- C# is fully object oriented language it implements all the concepts of OOPs. But VB.net is not fully OO language because some of the OOPs features like operator loading it does not have.
Is This Answer Correct ?

9 Yes 5 No 0 Ajay Bharti Re: Differences between VB.Net and C#, related to OOPS concepts Answer #5

Correcting some minor misinformation in prior answers: 1. As has already been stated, all .NET languages compile to MSIL, so given the same basic code structure, there is no difference in execution speed. Of course, either language may have features that encourage more or less efficient coding structures in certain circumstances, but the compiler optimizers usually catch many of these and optimize them accordingly. 2. VB.NET can indeed do operator overloading with the Operator statement (this may have been added to newer versions such as VS2005 since the previous answers were posted). 3. C++.NET can do true multiple inheritance (MI), but C# cannot. Indeed, C++ mainly does so with MFC, a pre-.NET unmanaged-code technology. The .NET Framework is designed not to need MI. In all .NET languages including VB.NET, the concept of Interfaces allows a limited form of an MIlike concept. A single Class can Implement multiple Interfaces, but Derive from only one parent Class. It can even do both in the same Class again, regardless of language.

4. In more modern versions of both languages (C# 2.0 & 3.0, VB.NET 9+), LINQ and many supporting technologies to enable and empower LINQ were added. These are very powerful in their own right as well as enabling the power of LINQ, and C# does indeed currently have an advantage here: lambdas are implemented much better in C# than in VB.NET (they can be multiline in C#, one expression only in VB.NET, and C# allows void-function [C-type language equivalent of Subs, namely, doesnt return a value] lambdas while the current VB.NET 9 still doesnt allow lambda Subs, only single-expression single-return-value Functions), C# allows Automatic Properties (a very powerful code saver, but useless for technlogies such as WPF that extend the concept of properties [e.g. WPF Dependency Properties]) while VB.NET doesnt yet (but will in .VB.NET 10 / VS2010 / NET Framework 4.0). Code Snippets mitigate the Automatic Properties thing anyway. Both have Extension Methods, Anonymous Types, etc. Some items not directly related to OOPS but often missed in discussions like this: 1. C# (like other C-derived languages) has post/pre inc/decrementer operators (++, --), plus operate-andassign operators (e.g. +=), bitwise shifts (<<, >>), short-circuiting logical operators, the ternary operator (?:), etc. While not widely known among those not familiar with it, VB.NET in its latest versions does currently have all of those except the post/pre inc/decrementers. Much of their functionality can be done with += or -= ("myCounter += 1" isn't that much harder to type nor convoluted than "myCounter++", but of course the latter does have the powerful advantage of being usable in expressions). 2. The VB.NET version of the ternary operator (introduced in VB.NET 8 or 9, IIRC) looks like a function, but is not: If(booleanExpression, trueValue, falseValue) -- this is not to be confused with the actual IIf(,,) function available all along which looks similar but is not shortcircuited and is a function, not an operator.

3. VB.NET now provides nullable value types, simply by putting a question mark after the Type ("Dim discount As Decimal?"). Nullables have a ".HasValue" Boolean property, and a read-only ".Value" property. A twooperand overload of the If() function-like operator allows for providing a default value in case of a Null (Nothing in VB.NET), similar to the ISNULL function in TSQL or a two-operand COALESCE function in ANSI standard SQL: salePrice -= If(discount, 0@) ' If the discount amount is Nothing (null), treat it as 0, avoiding a Null Value runtime error. Longer equivalent using ternary variant of If() operator: salePrice -= If(discount.HasValue, discount.Value, 0@) 4. Dates and times are standard VB.NET types that have existed since way back when in VB. C# still doesnt have them, and must resort to .NET classes. This means that you can have date and datetime literals in VB (simply delimited with #), while you have to parse a string or provide int parameters to initialize a Date or DateTime even to a known constant value in C#. While the C# optimizer may be smart enough to handle such circumstances, if it didnt, this is one obvious example of when VB.NET would produce faster code. Const santaDue As Date = #12/24/2009 12:59:59 PM# ' compiles right to an actual datetime literal constant! No run-time hit! vs. DateTime santaDue = DateTime.Parse("12/24/2009 12:59:59 PM"); // string literal has to be parsed and converted inefficient! DateTime santaDue = new DateTime(12, 24, 2009, 23, 59, 59); // somewhat more efficient (no string literal to

parse, but int literals have to be stuffed into date/time parts at run time), yet still not a pre-compiled literal constant. Not as intuitive to read, either. Id be interested to know if the C# optimizer can recognize such initializations using string or integer constants and optimize them.
How to know whether IIS is installed in your machine or not.

Re: How to know whether IIS is installed in your machine or not. Answer #1

Browse or navigate to the URL http://localhost/

If the IIS Welcome page appears IIS is installed and working properly. If the Under construction page error appears IIS may (Installed but not configured properly or IIS services might be stopped) or may not be installed.
Re: How to know whether IIS is installed in your machine or not. Answer #2

Click

inetmgr

in run ,if iis there,that wll open

Re: what is difference between IIS 5.0 and IIS 7.0 Answer #1

In IIS 6.0, the ASP.NET MMC snap-in provides IIS-related administration features for configuring ASP.NET. For more information. In IIS 7.0, the administration of ASP.NET applications is integrated more closely with IIS administration, and there is no separate snap-in. Instead, all IIS and ASP.NET configuration is done by using IIS Manager. Because IIS 7.0 configuration information is based on the .NET Framework configuration system, the Web.config file for an application that runs in IIS 7.0 contains both Web server and ASP.NET configuration settings. For example, in a Web.config file for an ASP.NET application running in IIS 7.0, you can specify the default

file to return when a browser does not request a specific file.In IIS 6.0 and earlier versions of IIS, this was a setting that was maintained in the IIS metabase.
Re: port no of FTP Answer #3

Active FTP: Command Port - 21 Data Port - 20


Re: portno for HTTP & HTTPS Answer #2

HTTP - 80 HTTPS - 443


Re: How do you create Virtual Root in IIS? Answer #1

just simple. FIRST CREATE THE NEWFOLDER IN THE ANY OF THE UR SYSTEM,THAT IS THE UR ORIGINAL ROOT FOLDER. goto start-->run--.type INETMGR--->GOTO DEFAULT WEBSITE-->RIGHTCLICK-->GOTO NEW-->SELECT NEW VIRTUAL DIRECTORY-->GIVE THE ALIAS NAME OF THE ROOT->CLICK NEXT-->GIVE YHE PATH OF THE ORIGINAL DIRECTORY-->CLICK NEXT--> CLICK FINISH--->VIRTUAL WILL BE CREATED
Is This Answer Correct ?

9 Yes 0 No 0 Bhaskar Re: How do you create Virtual Root in IIS? Answer #2

If the site is already existing then you simply open IIS manager, go to the site for which you need to create the virtual root [ virtual directory] Browse to that folder under the site, right click > properties > and Select create application.
Where are the IIS log files stored? Answer #1

To determine where your IIS log files are stored, please

execute the steps below on your server: 1. 2. Go to Start -> run type inetmgr

3. Find your web site under the tree on the left and right-click on it. 4. Choose properties

5. On the Web Site tab, you should see an option near the bottom that says "Active Log Format." Next to it is a Properties button. Click on the Properties button. 6. At the bottom of the General Properties tab, you'll see a box that contains the log file directory and the log file name. The full log path is comprised of the log file directory plus the first part of the log file name. For example, take the following case. 1. 2. Log file directory: C:\Windows\System32\LogFiles Log file name: W3SVC1\exyymmdd.log

3. Your full log path to put into SmarterStats would be: C:\Windows\System32\LogFiles\W3SVC1
Re: Where are the IIS log files stored? Answer #2

in system32
Re: Where are the IIS log files stored? Answer #3

The default location for the IIS log file is C:\windows\system32\LogFiles\W3SVC1. we can change this to any specific location.

What are different authentication types. How do you retreive user id in case of windows authentication. Answer #1

1.Window 2. Forms 3. Passport


Is This Answer Correct ?

6 Yes 6 No 0 Ram [Z Tech] Re: What are different authentication types. How do you retreive user id in case of windows authentication. Answer #2

Different Type of Authentications are Anonymous Authentication ( IUSR_COMPUTERNAME) Windows Integrated Authentication ( It uses NTLM or Kerberose, AuthType in IIS metabase) Basic Authentication ( Clear Text ) Digest Authentication Advance Digest Authentication Windows Form based authentication (using database at the blackened) IIS 6 includes. Passport Authentication. I believe Radius Authentication is one which can be included..! Authentication with Internet Authentication service IAS. How do you retrive UserID in case of Windows Authentication? HTTP header has the property Auth_Type = The authentication method that the server uses to validate users ( NTLM or Kerberos if Windows Intergrated Authenticaiton is used) AUTH_USER = Returns the raw authenticated user name Create a ASP page on webserver and drop the following lines to see the auth user..! :)

<% for each x in Request.ServerVariables response.write(x & "<br />") next %>
What are different authentication types. How do you retreive user id in case of windows authentication. Answer #3

Windows integrated authentication Anonymous authentication We can get the userid from user identity
Re: What is Web Garden?? Answer #1

All IIS Request process by worker process ( w3wp.exe)by default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden.
Is This Answer Correct ?

22 Yes 0 No 0 Bharath Kumar Re: What is Web Garden?? Answer #2

Garden with lots of webs and bettles.


What is Web Garden?? Answer #3

In App-pool properties, under PERFORMANCE tab we have an option for limiting the Request Queue going to Kernel. If it is set as 1000 and if the kernel receives 1500 requests, then the worker process fails of over loading. In order to avoid that 2 or more worker processes are assigned to a single application pool. If 1 one fails, the other is strarted. This concept is called as WEB GARDEN. The WebGarden option is available in the same properties Performance tab. There you can assign the number of worker processes for an application pool.

Re: What is the difference between connected environment and a disconnected environment? Answer #1

In connected,an application is constantly connected to data source. advantages : data concurrency is avoided because one user is connected to a data source and updating data,while another user cant made changes on data. In disconnected environment ,application isnt directly connected to data source.user use connection at once to retrieve data and connection closed after retreiving. limitation: data concurrency.
Is This Answer Correct ?

1 Yes 0 No 0 Pavithra Re: What is the difference between connected environment and a disconnected environment? Answer #2

Connected: In connected environment, the connection object is constantly opened to operate on the databases, and is closed after all the operation are performed. Advantages: fast retrieval of data, updated information is always accessed Disadvantage: security threats Disconnected: In the disconnected environment, the connection object is opened for the minimum amount of time, that is, the time when data is retrieved. After the data is retrieved from the database, the connection is closed, and all the operations like INSERT, UPDATE, DELETE, etc are performed offline. The

change during the operation can be reflected back to the database in the similar manner. Advantage: no security threats, increase in performance as connection is not constantly opened. Disadvantage: slow data retrival.
: How to insert multiple records in asp .net from Gridview to Sql Database with out using loop condition ? Answer #1

It is possible to insert many records and just save it to DB without loop.


Is This Answer Correct ?

5 Yes

0 No

0 Rajeev Re: How to insert multiple records in asp .net from Gridview to Sql Database with out using loop condition ? Answer #2

Ya we can do it by using XML.we can send records with XML format to the procedure as datatype xml in proc
Re: WHAT IS DIFF B/W VIEWS AND STORED PROCEDURE Answer #1

In views we can access data with a page,not like session b/w the pages. Stored Procedure use for Database communication... For Example: add,remove,update etc any record from database.
Is This Answer Correct ?

3 Yes 3 No 0 Asif Aslam Re: WHAT IS DIFF B/W VIEWS AND STORED PROCEDURE Answer #2

A view is a virtual table that consists of columns from one or more tables. Though it is similar to a table, it is stored in the database. It is a query stored as an object. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as base or

underlying tables. Once you have defined a view, you can reference it like any other table in a database. CREATE VIEW view_name [(column_name[,column_name].)] [WITH ENCRYPTION] AS select_statement [WITH CHECK OPTION] Where: A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure.
Re: what is type dataset? Answer #1

Dataset is collection of datatables.the collection generaly represented as *)tables-rows-columns-constraints DataSet ds;//declre variable ->ds.Tables["index"] ->ds.Tables.Rows[index] ->ds.Tables.Rows[rIndex].[cindex] ->ds.Tables.Columns[inedx] ->ds.tables.Constraints[index]
Is This Answer Correct ?

6 Yes

9 No

0 Shiva Re: what is type dataset? Answer #2

There are two type of Data set

When We create dataset programmely taht is weak type data set. like DataSet ds=new DataSet(); But when We Create a DataSet using XML Schema(Xsd) that is called strong type data set that has extension .xsd and create when we do working with LINQ to XML.
e: what is type dataset? Answer #3

A typed dataset is derived from the Dataset class and has an associated XML schema, which is created at the time of creation of the datset. An Untyped dataset does not have any associated XML shema.In an untyped dataset,the tables and columns are represented as collections.Because an XML shema is not created for an untyped datset,the structure of an untyped dataset is not known during compilation.
Can I use One Data Set for More than one Data Adapter?

No. We can't use.

Re: Can I use One Data Set for More than one Data Adapter? Answer #3

YEs By using Dispose method

Re: Can I use One Data Set for More than one Data Adapter? Answer #6

Yes, we can do that. But data from all adapters will get filled in the same default datatable of the dataset. That is, when we fill dataset with one adapter, the contents got filled in the table, and when we fill the same dataset again with the different adapters, the rows retrieved are appended to the already existing table of the dataset. So, if you want to just fill the dataset, you can do this, but obviously, this won't be useful in other scenarios.
Re: can we change the data in dataset? if yes what is the process? Answer #1

you can change data in dataset using

commandbuilder.

Re: Differentiate between Dataset and Recordset. Answer #1

Similar to the DataSet, a Recordset could be disconnected from its data store and therefore act as an in-memory cache of data. Of course, it could also be used in a connected model depending on the cursor options that were set. Although the Recordset object stored multiple versions of each column for each of its rows, it was not by nature able to represent multiple tables without the use of the Data Shape Provider. The Recordset was not XML-based and could not be serialized to XML easily or flexibly. Finally, a Recordset was not independent of a data store because it tracked a Connection object and through its methods could send queries to the data source to populate, update, and refresh its data. To that end, the Recordset contained functionality found in the ADO.NET DataSet, data reader, and data adapter objects.
Is This Answer Correct ?

17 Yes 4 No 0 Skmdali786 [MSD] Re: Differentiate between Dataset and Recordset. Answer #2

1) With Data set you can retrive data from database like oracle and SQL Server and manage them in one dataset, with recordset this is not possible. 2) All representation of Dataset is using XML while recordset uses COM.
Re: How to fetch the last inserted record in a particular table? Answer #1

CommanObject.CommandText="Select @@Identity";

** Note: Over a given connection if any insert statement is executed on a table with identity column , the back end sql-server for the connection initializes a parameter by name "@@Identity" with the value of Identity column for the last inserted record.
Re: How to fetch the last inserted record in a particular table? Answer #2

By using scope_identity
Re: How to fetch the last inserted record in a particular table? Answer #3

"select @@identity" @@identity is used to get the current transaction value . ** Note: Over a given connection if any insert statement is executed on a table with identity column , the back end sql-server for the connection initializes a parameter by name "@@Identity" with the value of Identity column for the last inserted record.
Is This Answer Correct ?

8 Yes 1 No 0 Nitin Kaushik Re: How to fetch the last inserted record in a particular table? Answer #4

If a table have identity column then u can fetch the last inserted record through following query: "select max(ID) from test"
Is This Answer Correct ?

2 Yes

9 No

0 Archana Re: How to fetch the last inserted record in a particular table? Answer #5

daer Archana your answer is nt complete so this s complete query fr last inserted record fetch from table select * from <tablename> where id=(select max(id) from <table name>)

Is This Answer Correct ?

27 Yes

1 No

0 Vimal Katiyar Re: How to fetch the last inserted record in a particular table? Answer #6

We can use the query like SELECT TOP 1 ID FROM table ORDER BY ID DESC
Is This Answer Correct ?

9 Yes 2 No 0 Skumar Re: How to fetch the last inserted record in a particular table? Answer #7

we get data from this Query ds.table[0].rows.count-1


Is This Answer Correct ?

3 Yes

4 No

0 Shashi Re: How to fetch the last inserted record in a particular table? Answer #8

if(ds.Tables["tablename"].Rows.Count>0) { ds.Tables{"tablename"].Rows.Count-1; }
Is This Answer Correct ?

3 Yes 3 No 0 Muskaan Re: How to fetch the last inserted record in a particular table? Answer #9

select * from tableName where rowid = (select max(rowid) from tableName); in oracle
Is This Answer Correct ?

1 Yes

0 No

0 Sudhakar Sakthivel Re: How to fetch the last inserted record in a particular table? Answer # 10

Through this statement, we can retrieve the same:

ds.Tables[0].Rows[ds.Tables[0].Rows.Count-1]
Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #1

Using Dataset first create data row then dr[index]=radiobuttonid.selecteditem;


Is This Answer Correct ?

11 Yes

7 No

0 Vasu Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #2

String radiovalue; radiovalue=radiobuttonid.selecteditem.Text; and pass that string to database


Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #3

if value is integer sqlcommand cmd=new sqlcommand("insert into tablename values("+convert.toint32(radiobutton1.selecteditem.text) +"",con);


Is This Answer Correct ?

4 Yes 4 No 0 Lalitkumar Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #4

RadioButton control doesn't have SelectedItem property. You need to use the Checked property of the RadioButton.
Is This Answer Correct ?

8 Yes 2 No 0 Claivan Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #5

If(Radiobutton.checked == true) { string str1 = "Male";

} insert into #t value(str1);


Is This Answer Correct ?

6 Yes

0 No

0 Vinay Kumar V Re: I want to ask u that if i add radio button in ado.net form,and how radion button data insert in SQL2005 Database... Answer #6

if(RadioButton1.checked == true) { string str="Male"; } sqlCommand cmd=new sqlcommand("Insert into tablename values("'+str+'")",con);
Re: what is ado.net Answer #1

ADO.NET provides access to data sources such as SQL. The application can use ado.net to connect to data sources to retrieve, manipulate and update data.
Is This Answer Correct ?

15 Yes 0 Mithun Re: what is ado.net Answer #2

1 No

ado.net is collection of managed providers that provides communication to the application with the datasources.
Re: what is ado.net Answer #3

ADO.net means Activex Data Object. ADO.net provides the activ coonectivity with the database at runtime. We can do the operations which are related to the database..
Is This Answer Correct ?

8 Yes 0 Archana Re: what is ado.net Answer #4

0 No

It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by

programmers to access and modify data stored in relational database systems, though it can also access data in nonrelational sources
Is This Answer Correct ?

4 Yes

1 No

0 Rajesh Re: what is ado.net Answer #5

ado.net is one of the nativedriver in .net. ado.net is the set of classes that expose data access service to .net programmer
Is This Answer Correct ?

2 Yes 0 Narra.rajeevreddy Re: what is ado.net Answer #6

1 No

ADO.NET is the technology that is used to access the database from the .NET platform.
Re: IF we have lot of records in Database. How we can handle them? Answer #1

Increase the execution timeout in ADO.NET


Is This Answer Correct ?

8 Yes 1 No 1 Naren Re: IF we have lot of records in Database. How we can handle them? Answer #2

You can handle Large data by practicing some design patterns like, using stored procedures rather than Statements, Use coloum names rather tahn * when fetching the statements etc..
Re: IF we have lot of records in Database. How we can handle them? Answer #3

You can set this value in web.config. For example, to change the timeout for one specific page: <location path="somefile.aspx"> <system.web> <httpRuntime executionTimeout="180"/> </system.web> </location>

Hope that helps. Ashish Bharadwaj,Noida(delhi) mail:-ashishsrm85@gmail.com


Is This Answer Correct ?

1 Yes 1 No 0 Ashish Bharadwaj Re: IF we have lot of records in Database. How we can handle them? Answer #4

If we have lot of records to handle with safly and fastly we must use Triggers ,Stored procedure to maintain accuracy ,and Indexing for fast retrival of data
Re: What is the main difference between ADO and ADO.Net Answer #1

ADO- Connection-Oriented Architecture Use Record Set Communicate in Binary mode Ado.net Dis-connected architecture Use DataSet,Adapter Parse Data in XML mode
Re: What is the main difference between ADO and ADO.Net Answer #2

ADO was a connected data access model, which means that when a connection to the database is made, the connection remains open until the application is closed. ADO.NET is disconnected database access model, which means when an application interacts with the database, the connection is opened to serve the request of the application, and is closed as soon as the request is completed. All data is presented in XML, as compared to ADO.
Re: What is the main difference between ADO and ADO.Net Answer #3

The old ADO (ActiveX Data Object) has evolved to ADO.NET in the .NET Framework. The ADO.NET object is a lightweight object. The ADO Recordset was a huge object in ADO. It provided the ability to support multiple types of cursors. It provided fast lightweight "firehose" cursor and also supported a disconnected client-side cursor that supported tracking, optimistic locking, and automatic batch updates of a central database. However, all of this functionality was difficult to customize. ADO.NET breaks the functionality of the ADO object to multiple classes, thereby allowing a focused approach to developing code. The ADO.NET DataReader is equivalent to the "firehose" cursor. The DataSet is a disconnected cache with tracking and control binding functionality. The DataAdapter provides the ability to completely customize how the central data store is updated with the changes to a DataSet.
Re: What is the main difference between ADO and ADO.Net Answer #4

ADO- Connection-Oriented Architecture Use Record Set Communicate in Binary mode Ado.net Dis-connected architecture Use DataSet,Adapter Parse Data in XML mode
Re: How to sort the data in Datatable Answer #1

pass the datatable in dataview object and call the sort method on dataview dataview dv=new dataview(dt) dv.sort that's it

Re: How to sort the data in Datatable Answer #2

I think the above answer is correct.Another one method is DataTable dt=new DataTable(); DataRow[] dr=dt.Select("Filter Expression","Sort expression"); Here Sort expression is , for eg.Address is one of the field in dt. Then DataRow[] dr=dt.Select("","Address ASC"); But in this method is have the Datarow array.So you can use another one method,I explain below. DataView dv=new DataView(Datatable,Filter Exp,Sort Exp,Dataviewrowstate) Eg is DataView dv=new DataView(dt,"","Address ASC,DataViewVowState.CurrentRows); Here we can copy this Dataview to datatable or use this same dataview instead of datatable.
Re: Write steps of retrieving data using ado.net ? Answer #1

we can use two ways to retrieve the data from database 1 -> data reader 2 -> data adapter when you use datareader create connection object and open the connection SqlCommand cmd = new SqlCommand(sql,con); cmd.CommandType = CommandType.Text; SqlDataReader sread = cmd.ExecuteReader(); while(sread.Read()) {

String data1 = sread.GetString(0); int data2 = sread.GetValue(1); String data3 = sread.GetString(2); } when u use the dataadapter create the connection and open SqlDataAdapter sda = new SqlDataAdapter(sql,con); DataSet ds = new DataSet(); sda.Fill(ds,"customer"); then use can get the data in row wise or directly assign the data to the controls through datasource. i think its enough.If i did any mistake correct me.
Re: Write steps of retrieving data using ado.net ? Answer #2

We can retrieve data in following ways in .net 1st we have to create connection object through sqlclient or oledb provider.then open connection 2nd We can choose datacommands or data adapter(by sqlclint or oledb dataprovider system.data system.data.oledb //to oledb adapter system.data.sqlclient //to sqlclient adapter dim con as new connection con=("provider=oledb;initial catalog=databasename;userid=sa;paswd=;data source=servername;") con.open dim query as string="select* from tabel" dim ad as new oledb.oledbprovider(query,con) dim ds as dataset ad.fill(ds) dim dt as new datatable() dt=ds.table(0) //is for ist tabel dim dr() as datarow //it is array becouse it contain all rows and coulmn for table dr()=dt.select("") //blank for all coulmns and rows

for i as integer=0 to dr.length-1.tostring if dr(i)("empid")=textbox.text then listbox1.items.add(dr(i)("firstname")& dr(i)("lastname")& dr(i)("email")) //it will add records of perticular row that matches to the textbox text in listbox.suppose u enter a001 if it is valide id then the all records of a001 r added into the list box.// next it will work fine.try thanks
Re: Write steps of retrieving data using ado.net ? Answer #3

Take a gridview control in ur design add using system.data.sqlclient; using.system.data; // give a connection string to database sqlconnection con= new sqlconnection("conn"); //in button click event write following sqldataadapter da=new sqldataadapter("select * from (tablename)",con); dataset ds=new dataset(); da.fill(ds,"tablename"); gridview1.datasource=ds; gridview1.datamember="tablename"; gridview1.databind(); try out this

You might also like