use oops
-
Upload
mano-haran -
Category
Documents
-
view
217 -
download
0
Transcript of use oops
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 1/126
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 thevariables 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
advantageoops 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 2/126
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 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. By the 1980’s,
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 thatare 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. Theterm 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 3/126
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 for
object oriented programming are Classes Objects and Methods. However there are
a few more concepts that you will want to become familiar with. These are
Inheritance Abstraction Polymorphism Event and Encapsulation. In this article I will
be using the class Cats as an
What is Object Oriented Programming?
What is Object Oriented Programming There are a number of commoncharacteristics 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 object-
oriented 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 4/126
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 designthat 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 andbehaviors. 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 5/126
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 theproper 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 thatprogrammers 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 6/126
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 setof 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 OOPterms 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, hascreated 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 7/126
{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 havepublic 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. Touse it, you don't need to know how internally LCD screens, keyboard, web camera, battery,
wireless antenna, speaker’s 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 internaldetails 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 memberfunctions.
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.
Let’s try to understand by a practical example:-
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 8/126
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 can’t access private data through object.But here it isaccessible.:)
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 outsidethe class
Class1 obj = new Class1(); // obj.i =10; //Error can’t access private data through object.
obj.j =10; // obj.k=10; //Error can’t 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 can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names onlyClass1.y = 10;
}What if Main is inside another assembly
[STAThread]
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 9/126
static void Main(){
//Access specifiers comes into picture only when you create object of class outsidethe class
Class1 obj = new Class1(); // obj.i =10; //Error can’t access private data through object.
obj.j =10; // obj.k=10; //Error can’t access protected data through object.
// obj.m=10; // Error can’t access internal data outside assembly // obj.n=10; // Error can’t access internal data outside assembly
// obj.s =10; //Errror Static data can be accessed by class names onlyClass1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names onlyClass1.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 andeliminating 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. Througheffective 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 tounderstand 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");}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 10/126
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 thewrite () 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 executedChild Class Constructor executed
Write method in Base Class executed
this output proves that when we create an instance of a child class, the base classconstructor 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. Thebase 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 fromClass 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-levelinheritance. 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-levelinheritance Class has access to A_Method(),B_Method() and C_Method().
Note: Classes can inherit from multiple interfaces at the same time. Interview Question:
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 11/126
How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talkabout 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 thebase 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. Classmembers 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 reporta compile time error.
Using System;Public class A
{Public void M1 ()
{}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 12/126
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 callthe 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 childobject 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:
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 13/126
When a message can be processed in different ways is called polymorphism. Polymorphismmeans 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 duringruntime.
• 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 earlybinding.
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 14/126
{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 willwork 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 carriesout 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)
{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 15/126
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 andthe 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 derivedclass using override keyword.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 16/126
Derived class method will completely overrides base class method i.e. when we refer baseclass 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 methodDerivedClass 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, objectinitialization 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 allocationand 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 17/126
• 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. Forexample, if you declare a constructor with protected access, only derived classes and friendscan use it to create class objects.
The compiler automatically calls constructors when defining class objects and callsdestructors when class objects go out of scope. A constructor does not allocate memory for
the class object it’s this pointer refers to, but may allocate storage for more objects than itsclass 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 thecorresponding 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 theirpractical implementation in C#. We will discuss here basics of OOPS
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 18/126
including Interfaces, Access Modifiers, inheritance, polymorphism etc. This ismy 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 aspecific set of characteristics and is able to perform a set of actions.
Object-oriented languages provide abstraction via classes. Classes define theproperties and methods of an object type.
Examples:
• You can create an abstraction of a dog with characteristics, such ascolor, height, and weight, and actions such as run and bite. The
characteristics are called properties, and the actions are calledmethods.
• 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 theother hand, when we are working with simple data types such as Integer, weare working with the actual value rather than a reference.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 19/126
When we create a new object using the New keyword, we store a referenceto 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 objectvia the MyDraw variable. This variable holds a reference to the object.
Now we have a second variable, which also has a reference to that sameobject. We can use either variable interchangeably, since they bothreference the exact same object. The thing we need to remember is that thevariable we have is not the object itself but, rather, is just a reference orpointer to the object itself.
Early binding means that our code directly interacts with the object, bydirectly 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 theobject. Early binding also allows the IDE to use IntelliSense to aid ourdevelopment efforts; it allows the compiler to ensure that we are referencingmethods that do exist and that we are providing the proper parametervalues.
Late binding means that our code interacts with an object dynamically atrun-time. This provides a great deal of flexibility since our code literallydoesn't care what type of object it is interacting with as long as the objectsupports 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 syntaxchecking is possible but we get unprecedented flexibility in exchange.
If we enable strict type checking by using Option Strict On at the top of ourcode 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 useof 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 aninstance of a class, by a class's internal code, and by any descendants of aclass.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 20/126
Private is hidden and usable only by the class itself. No code using a classinstance can access a private member directly and neither can a descendantclass.
Protected members are similar to private ones in that they are accessibleonly by the containing class. However, protected members also may be usedby a descendant class. So members that are likely to be needed by adescendant class should be marked protected.
Internal/Friend is public to the entire application but private to anyoutside applications. Internal is useful when you want to allow a class to be
used by other applications but reserve special functionality for theapplication that contains the class. Internal is used by C# and Friend byVB .NET.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 21/126
Protected Internal may be accessed only by a descendant class that'scontained in the same application as its base class. You use protected
internal in situations where you want to deny access to parts of a classfunctionality 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. Theobject's data and behaviors are contained within the object, so a client
application can treat the object like a black box accessible only through itsinterface. This is a key object-oriented concept called Encapsulation. Theidea is that any programs that make use of this object won't have directaccess to the behaviors or data-but rather those programs must make use of our object's interface.
There are three main parts of Object:
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 22/126
1. Interface2. Implementation or Behavior3. Member or Instance variables
Interface
The interface is defined as a set of methods (Sub and Function routines),properties (Property routines), events, and fields (variables or attributes)that are declared Public in scope.
Implementation or Behavior
The code inside of a method is called the implementation. Sometimes it isalso called behavior since it is this code that actually makes the object douseful work.Client applications can use our object even if we change the implementation-as long as we don't change the interface. As long as our method name andits parameter list and return data type remain unchanged, we can changethe 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 allowsour code to continue to run without change. However, it is not semantic-meaning that, just because our code continues to run, doesn't mean itcontinues 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 classis absolutely identical in terms of its interface and its implementation-theonly 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 codewithin our class. Typically member variables are Private in scope-availableonly to the code in our class itself. They are also sometimes referred to asinstance variables or as attributes. The .NET Framework also refers to themas fields.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 23/126
We shouldn't confuse instance variables with properties. A Property is a typeof method that is geared around retrieving and setting values, while aninstance variable is a variable within the class that may hold the valueexposed by a Property.
Interface looks like a class, but has no implementation.
The only thing it contains is definitions of events, indexers, methods and/orproperties. The reason interfaces only provide definitions is because they areinherited by classes and structs, which must provide an implementation foreach interface member defined. So, what are interfaces good for if theydon't implement functionality? They're great for putting together plug-n-playlike architectures where components can be interchanged at will. Since allinterchangeable components implement the same interface, they can beused without any extra programming. The interface forces each componentto expose specific public members that will be used in a certain way.
Because interfaces must be defined by inheriting classes and structs, theydefine a contract. For instance, if class foo inherits from the IDisposableinterface, it is making a statement that it guarantees it has the Dispose()method, which is the only member of the IDisposable interface. Any codethat wishes to use class foo may check to see if class foo inheritsIDisposable. When the answer is true, then the code knows that it can callfoo.Dispose().
Defining an Interface: MyInterface.c
interface IMyInterface{
void MethodToImplement();}
Above listing shows defines an interface named IMyInterface. A commonnaming convention is to prefix all interface names with a capital "I", but thisis not mandatory. This interface has a single method namedMethodToImplement(). This could have been any type of method declarationwith different parameters and return types. Notice that this method does not
have an implementation (instructions between curly braces- {}), but insteadends with a semi-colon, ";". This is because the interface only specifies thesignature 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 24/126
Using an Interface: InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface{
public void MethodToImplement(){
Console.WriteLine("MethodToImplement() called.");}
}
The InterfaceImplementer class in above listing implements the IMyInterfaceinterface. Indicating that a class inherits an interface is the same asinheriting 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 bedeclared public only. It does this by implementing the MethodToImplement()method. Notice that this method implementation has the exact samesignature, parameters and method name, as defined in the IMyInterfaceinterface. Any difference will cause a compiler error. Interfaces may alsoinherit other interfaces. Following listing shows how inherited interfaces areimplemented.
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 theinterface it inherits, IParentInterface. When one interface inherits another,
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 25/126
any implementing class or struct must implement every interface member inthe entire inheritance chain. Since the InterfaceImplementer class in abovelisting 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. Interfacesmay also be inherited by other interface. Any class or struct that inherits aninterface must also implement all members in the entire interfaceinheritance chain.
Inheritance is the idea that one class, called a subclass, can be based onanother class, called a base class. Inheritance provides a mechanism forcreating hierarchies of objects.
Inheritance is the ability to apply another class's interface and code to yourown class.
Normal base classes may be instantiated themselves, or inherited. Derivedclasses can inherit base class members marked with protected or greateraccess. The derived class is specialized to provide more functionality, inaddition to what its base class provides. Inheriting base class members inderived 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 aderived class:Call a method on the base class that has been overridden by anothermethod. Specify which base-class constructor should be called when creatinginstances of the derived class. A base class access is permitted only in aconstructor, 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 ispossible to call the Getinfo method on the base class, from within thederived class.
// Accessing base class members
using System;
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 26/126
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();
}
}
OutputName: John L. MalgraineSSN: 444-55-6666Employee ID: ABC567EFG
Base class constructors can be called from derived classes. To call a baseclass constructor, use the base() constructor reference. This is desirablewhen it's necessary to initialize a base class appropriately.
Here's an example that shows the derived class constructor with an addressparameter:
abstract public class Contact{
private string address;public Contact(string b_address)
{this.address = b_address;
}}
public class Customer : Contact
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 27/126
{public Customer(string c_address) : base(C_address)
{}
}
In this code, the Customer class does not have an address, so it passes theparameter to its base class constructor by adding a colon and the basekeyword with the parameter to its declaration. This calls the Contactconstructor with the address parameter, where the address field in Contactis initialized.
One more example which shows how base-class constructor is called whencreating instances of a derived class:
using System;public class MyBase
{int num;
public MyBase(){
Console.WriteLine("In MyBase()");}
public MyBase(int i){
num = i;Console.WriteLine("in MyBase(int i)");
}
public int GetNum(){
return num;
}}
public class MyDerived : MyBase{
static int i = 32; // This constructor will call MyBase.MyBase()
public MyDerived(int ii) : base(){
} // This constructor will call MyBase.MyBase(int i)
public MyDerived() : base(i)
{}public static void Main()
{MyDerived md = new MyDerived(); // calls public MyDerived() : base(i) and
// passes i=32 in base classMyDerived md1 = new MyDerived(1); // call public MyDerived() : base(i)
}}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 28/126
Outputin MyBase(int i)in MyBase()
The following example will not compile. It illustrates the effects of notincluding 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 classconstructor. This is obviously a bug, since the address field will never beinitialized.
When a class has no explicit constructor, the system assigns a defaultconstructor. The default constructor automatically calls a default or
parameterless base constructor. Here's an example of automatic defaultconstructor generation that would occur for the preceding example:
public Customer() : Contact()
{}
When a class does not declare any constructors, the code in this example isautomatically generated. The default base class constructor is calledimplicitly when no derived class constructors are defined. Once a derivedclass 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 thosemembers have protected or greater access. Simply use the member name in
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 29/126
the appropriate context, just as if that member were a part of the derivedclass 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 callsthe FullAddress() method in its base class, Contact. All classes have fullaccess to their own members without qualification. Qualification refers tousing a class name with the dot operator to access a class member-MyObject.SomeMethod(), for instance. This shows that a derived class canaccess 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. Sofollowing is an error:public static virtual void GetSSN()
• You can't call static methods of base class from derived class usingbase 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 30/126
}}
now you can't call this method using base.GetInfo() from derived classinstead 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 derivedclass, you can't use base class method by using base keyword inderived class. Also when you will create an instance of derived class, itwill call derived class method and you will only be able to access baseclass method when you will create instance of base class.
•
You can't decrease access level of a method in derived class when youare overriding a base class method in derived class, vice versa ispossible.Means you can make protected method of base class to public inderived class.
The "this" keyword refers to:
• the current instance for which a method is called. Static memberfunctions do not have a this pointer. The this keyword can be used toaccess 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;
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 31/126
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 theconstructor Employee and not to private variable name in the class. In thiscase 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, orvariable initializer of a field declaration.
In this example, this is used to qualify the Employee class members, nameand alias, which are hidden by similar names. It is also used to pass anobject 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()
{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 32/126
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();}}
OutputName: John M. TrainerAlias: jtrainerTaxes: $240.00
Abstract Classes
Abstract classes are a special type of base classes. In addition to normalclass members, they have abstract class members. These Abstract classmembers are methods and properties that are declared without animplementation. All classes derived directly from abstract classes mustimplement all of these abstract methods and properties.
Abstract classes can never be instantiated. This would be illogical, becauseof the members without implementations.So what good is a class that can'tbe instantiated? Lots! Abstract classes sit toward the top of a classhierarchy. They establish structure and meaning to code. They make
frameworks easier to build. This is possible because abstract classes haveinformation 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(){
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 33/126
// statements...}
public abstract void generateReport();abstract public string Name
{get;
set;}
}
Contact, is an abstract class. Contact has two abstract members, and it hasan abstract method named generateReport(). This method is declared withthe abstract modifier in front of the method declaration. It has noimplementation (no braces) and is terminated with a semicolon. The Nameproperty is also declared abstract. The accessors of properties areterminated 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 34/126
}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 andSiteOwner. Both of these derived classes implement the abstract membersof the Contact class. The generateReport() method in each derived class hasan override modifier in its declaration. Likewise, the Name declarationcontains an override modifier in both Customer and SiteOwner.
C# requires explicit declaration of intent when overriding methods. Thisfeature promotes safe code by avoiding the accidental overriding of baseclass methods, which is what actually does happen in other languages.
Leaving out the override modifier generates an error. Similarly, adding anew modifier also generates an error. Abstract methods must be overriddenand cannot be hidden, which the new modifier or the lack of a modifierwould be trying to do.
The most famous of all abstract classes is the Object class. It may bereferred to as object or Object, but it's still the same class. Object is thebase class for all other classes in C#. It's also the default base class when abase class is not specified. The following class declarations produce the sameexact results:
abstract public class Contact : Object{
// class members}
abstract public class Contact{
// class members}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 35/126
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 derivedclasses to implement.
Difference between Interface and Abstract Class
• Interfaces are closely related to abstract classes that have allmembers abstract.
• For an abstract class, at least one method of the class must be anabstract 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 elsemust 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 vizmethods, properties, events and indexes. An interface thus cannotcontain constants, fields, operators, constructors, destructors, staticconstructors, or types.
• Also an interface cannot contain static members of any kind. Themodifiers abstract, public, protected, internal, private, virtual, overrideis disallowed, as they make no sense in this context.
• Class members that implement the interface members must bepublicly accessible.
Overriding Summery:
A derived class may override a virtual method of the base class with thekeyword override. The following restrictions must be followed.
• Keyword override is used in the definition of child class method that isgoing to override the base class's virtual method.
• The return type must be the same as the virtual method have in baseclass.
• 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 36/126
• The virtual methods can be sealed in the child or derived classes toprevent further modifications in the implementation of the virtualmethod in the derived classes, by declaring them as sealed methods.
Hiding Base Class Members
Sometimes derived class members have the same name as a correspondingbase 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 thebase class member. Users of the derived class won't be able to see thehidden member; they'll see only the derived class member. The followingcode 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 methodnamed FullAddress(). The FullAddress() method in the SiteOwner class hidesthe 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 theFullAddress() method of the Contact class.
Although a base class member may be hidden, the derived class can stillaccess it. It does this through the base identifier. Sometimes this isdesirable. It is often useful to take advantage of the base class functionality
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 37/126
and then add to it with the derived class code. The next example shows howto 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 iscalled from within the FullAddress() method of the SiteOwner class. This isaccomplished with a base class reference. This provides another way toreuse code and add on to it with customized behavior.
Versioning
Versioning, in the context of inheritance, is a C# mechanism that allowsmodification of classes (creating new versions) without accidentally changingthe meaning of the code. Hiding a base class member with the methodspreviously described generates a warning message from the compiler. This isbecause of the C# versioning policy. It's designed to eliminate a class of problems associated with modifications to base classes.
Here's the scenario: A developer creates a class that inherits from a third-
party library. For the purposes of this discussion, we assume that theContact class represents the third-party library. Here's the example:
public class Contact{
// does not include FullAddress() method}
public class SiteOwner : Contact{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 38/126
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 libraryupdate their code. Part of this update includes a new member in a base classwith 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 differentfunctionality than the derived class method. In other languages, thisscenario would break the code because of implicit polymorphism. However,this does not break any code in C# because when the FullAddress() methodis called on SiteOwner, it is still the SiteOwner class method that gets called.
This scenario generates a warning message. One way to eliminate thewarning 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()
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 39/126
{}
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 40/126
{name = value;
siteHits = 0;}
}}
public class Test{
public static void Main(){
WebSite mySite = new WebSite("Le Financier","http://www.LeFinancier.com","FancyFinancial 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'sintent. Placing the new modifier in front of the derived class member statesthat 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 classmember. With C#, the method in the derived class is called when an objectof the derived class type is used. Likewise, the method in the base class iscalled when an object of the Base class type is called. Another problem thispresents is that the base class may present some desirable new featuresthat wouldn't be available through the derived class.
To use these new features requires one of a few different workarounds. Oneoption would be to rename the derived class member, which would allow
programs to use a base class method through a derived class member. Thedrawback to this option would be if there were other classes relying upon theimplementation of the derived class member with the same name. Thisscenario will break code and, for this reason, is considered extremely badform.
Another option is to define a new method in the derived class that called thebase class method. This allows users of the derived class to have the new
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 41/126
functionality of the base class, yet retain their existing functionality with thederived class. While this would work, there are maintainability concerns forthe derived class.
Sealed Classes
Sealed classes are classes that can't be derived from. To prevent otherclasses from inheriting from a class, make it a sealed class. There are acouple good reasons to create sealed classes, including optimization andsecurity.
Sealing a class avoids the system overhead associated with virtual methods.This allows the compiler to perform certain optimizations that are otherwiseunavailable with normal classes.
Another good reason to seal a class is for security. Inheritance, by its verynature, dictates a certain amount of protected access to the internals of apotential base class. Sealing a class does away with the possibility of corruption by derived classes. A good example of a sealed class is the Stringclass. 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 issealed, it can't be inherited by the CustomerInfo class.The CustomerStatsclass was meant to be used as an encapsulated object in another class. Thisis shown by the declaration of a CustomerStats object in the Customer class.
public class Customer{CustomerStats myStats; // okay
}
Polymorphism
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 42/126
Polymorphism is reflected in the ability to write one routine that can operateon objects from more than one class-treating different objects from differentclasses in exactly the same way. For instance, if both Customer and Vendorobjects have a Name property, and we can write a routine that calls theName 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 onlyhave those properties and methods that all vehicles have, a few of whichmight include paint color, number of doors, accelerator, and ignition. Theseproperties 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 andmethods. Instead, polymorphism is the implementation of an interface. If the car, truck, and semitruck all implement the same vehicle interface, thenthe client code for all three classes can be exactly the same.
C# gives us polymorphism through inheritance. C# provides a keywordvirtual that is used in the definition of a method to support polymorphism.
Child class are now free to provide their own implementation of this virtualmethod, that is called overriding. The following points are importantregarding 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 thereference type at runtime it is actually denoting to, then the appropriatemethod is called from the class of the reference type.
When a virtual method is called, runtime check (late method binding) ismade to identify the object and appropriate method is invoked, all this isdone 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 theway non-virtual methods are called. But the behavior of virtual method isuseful in many ways; the functionality they provide is fair enough to bearthis slight loss of performance.
Implementing Polymorphism
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 43/126
The key factor here is the ability to dynamically invoke methods in a classbased on their type. Essentially, a program would have a group of objects,examine the type of each one, and execute the appropriate method. Here'san 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 designtime we have to decide which method we need to invoke while inheriting theclass.
Polymorphism is the capability of a program to carry out dynamic operationsby implementing methods of multiple derived classes through a commonbase class reference. Another definition of polymorphism is the ability totreat different objects the same way. This means that the runtime type of anobject determines its behavior rather than the compile-time type of itsreference.
C# and oops concepts-keywords
C# and oops concepts-keywords
Method: A method is a code block containing a series of statements.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 44/126
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 usingkeywords “ 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 anddouble quote etc are called escape characters.
Ex: \+ tab
\n next line
\” double quotes
\’ single quotes
\0 null
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 45/126
\v vertical tab
Arithmetic operators: The operators which are used for performing arithmetic operationsare 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 : falsevalEx: 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 codethen 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 46/126
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, publicand 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 wasinherited.
Ex: class Honda
{----------}
Class accord: Honda
{------------}
Abstraction: Abstraction is the process in which if we don’t define a function in a class,
then we can give that function’s 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 implementationis 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
{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 47/126
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;
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 48/126
}
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 wewant 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 asingle 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 deleterecords. To do that instead of creating four Stored Procedures to perform these tasks I willcreate a single Stored Procedure to satisfy my requirements and I will access it in codebehind 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 toSQL 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 asinsert, select, update and delete operations on a table and so on which is stored in a SQLdatabase.
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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 49/126
Now we have a table to perform these operations. Now let us start to create the StoredProcedure.
The Stored Procedure is created using the keyword Create Procedure followed by theprocedure 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 tothis 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-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------asBeginSET NOCOUNT ON;
If @Action='Insert' --used to insert records
BeginInsert Into employee (FirstName,MName,LastName)values(@Fname,@MName,@Lname)End
else if @Action='Select' --used to Select recordsBeginselect *from employeeend
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 50/126
else if @Action='Update' --used to update recordsBegin update employee set FirstName=@Fname,MName=@MName,LastName=@Lname whereid=@idEndElse If @Action='delete' --used to delete records
Begindelete from employee where id=@idendEnd
In the above Stored Procedure throught comments I have clearly explained whichblock 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 parameterpassed to the Stored Procedure the particular block will be executed because I havekept 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 differentnumber of parameters but not the same number of parameters to the Stored Procedure toperform 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 thekeyword exec followed by the procedure name and the parameter list. I have explained howto use it below.
Inserting the Records into the Employee table that we created with the EmpEntryprocedure; 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 therecords 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'
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 51/126
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 codebehind on a button click. I hope this article is useful for all readers.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 52/126
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 beOverloaded 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(intnumber).
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 itdefines 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 :
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 53/126
• 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 globalfunctions. You dont have to create an instance to access the code thusreducing 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 54/126
• A Static Constructor is called to automatically initialize the class before thefirst 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 accesslevel 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 55/126
• Usage : virtual(base class)/new(derived class) and public(baseclass)/new(derived class) , So it is not a replacement for override modifierbut 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 overridedin 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
}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 56/126
static void Main()
{
Transaction obj = new Transaction();
IOrderDetails OD = obj;OD.ShowDetails();
ICustDetails CD = obj;
CD.ShowDetails();
}
}
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 Let’s 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 57/126
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 namespacecan 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 58/126
[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()
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 59/126
…
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 60/126
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 inthe 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
{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 61/126
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 62/126
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 doesn’t
occupies memory.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 63/126
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 typeand 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, whileClass 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 (no-
argument 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.
EncapsulationWrapping 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 64/126
{
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 supposedto 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)
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 65/126
//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;
}
}
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 66/126
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 itsclass.
•
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 cannotreturn 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 calleddefault constructor. Eg: class A, default constructor is A().
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 67/126
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 68/126
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 69/126
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()
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 70/126
{
}
//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, howeveryou can force the garbage collection to run at a certain point in your code bycalling System.GC.Collect().
• Advantage of Garbage collection : It prevents programming error that couldotherwise occur by incorrectly deleting or failing to delete objects.
Enumeration
Enumeration improves code readability. It also helps in avoiding typing mistake.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 71/126
Concept of Heap and Stack
Local Variables Stack
Free Memory
(Larger Memory Area than Stack).
Heap
Global VariablesPermanent Storage area
Program Instruction
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 objecttype 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 72/126
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 valueparameter to be passed by reference. Note: variable “must” be initialized before it
is passed into a method.
out keyword
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 73/126
out keyword is used for passing a variable for output purpose. It has same concept
as ref keyword, but passing a ref parameter needs variable to be initialized while
out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.
Note: You must assigned value to out parameter in method body, otherwise the method won’t
compiled.
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.
InheritanceThe process of sub-classing a class to extend its functionality is called Inheritance.
It provides idea of reusability.
Order of Constructor execution in Inheritance
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 74/126
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 toparent 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?
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 75/126
No. A class can inherit from only one base class, however a class can implements
many interface, which servers some of the same purpose without increasing
complexity.
How many types of Access Modifiers.
1) Public – Allows the members to be globally accessible.
2) Private – Limits the member’s access to only the containing type.
3) Protected – Limits the member’s access to the containing type and all classes
derived from the containing type.
4) Internal – Limits the member’s access to within the current project.
Method OverloadingMethod 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 76/126
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 77/126
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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 78/126
• 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 theimplementation of the members, only the parameters they take and thetypes of values they will return. Implementation of an interface is left entirelyto 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, Trainor Boat might implement this interface and thus are able to interact with theDriver object. The Driver object is unaware of which interface implementationit is interacting with; it is only aware of the interface itself.
• Example2, an interface named IShape, which defines a single methodCalculateArea. A Circle class implementing this interface will calculate itsarea differently than a Square class implementing the same interface.However, an object that needs to interact with an IShape can call theCalculateArea 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 79/126
}
}
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 stillinterface and not class.
• If a class that implements an interface does not implements all the methodsof the interface, then the class becomes an abstract class and cannot beinstantiated.
• Both classes and structures can implement interfaces, including multipleinterfaces.
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, interfacesdo not provide implementation. They are implemented by classes, and defined as separate entitiesfrom classes. Even though class inheritance allows your classes to inherit implementation from a baseclass, 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 invariantlevel of functionality in some methods, but leave the implementation of other methods until a specificimplementation of that class is needed. They also version well, because if additional functionality isneeded in derived classes, it can be added to the base class without br
Difference between Interface and Abstract Class
Interfaces vs. Abstract Classes
Feature Interface Abstract class
Multiple
inheritance
A class may implement
several interfaces.
A class may extend only one
abstract class.
Defaultimplementation
An interface cannot provideany code at all, much lessdefault code.
An abstract class can providecomplete code, default code,and/or just stubs that have to beoverridden.
Constants Static final constants only,can use them withoutqualification in classes thatimplement the interface. Onthe other paw, theseunqualified names pollutethe namespace. You can usethem and it is not obviouswhere they are coming from
Both instance and static constantsare possible. Both static andinstance intialiser code are alsopossible to compute the constants.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 80/126
since the qualification isoptional.
Third partyconvenience
An interface implementationmay be added to anyexisting third party class.
A third party class must berewritten to extend only from theabstract class.
Is-a vs -able orcan-do
Interfaces are often used to
describe the peripheralabilities of a class, not itscentral identity, e.g. anAutomobile class mightimplement the Recyclableinterface, which could applyto many otherwise totallyunrelated objects.
An abstract class defines the coreidentity of its descendants. If youdefined a Dog abstract class thenDamamation descendants areDogs, they are not merely dogable.Implemented interfaces enumeratethe general things a class can do,not the things a class is.
Plug-in
You can write a newreplacement module for an
interface that contains notone stick of code in commonwith the existingimplementations. When youimplement the interface, youstart from scratch withoutany default implementation.You have to obtain yourtools from other classes;nothing comes with theinterface other than a fewconstants. This gives youfreedom to implement aradically different internal
design.
You must use the abstract class as-is for the code base, with all itsattendant baggage, good or bad.The abstract class author hasimposed structure on you.Depending on the cleverness of theauthor of the abstract class, thismay be good or bad. Another issuethat's important is what I call"heterogeneous vs. homogeneous."If implementors/subclasses arehomogeneous, tend towards anabstract base class. If they areheterogeneous, use an interface.(Now all I have to do is come upwith a good definition of hetero/homogeneous in thiscontext.) If the various objects areall of-a-kind, and share a commonstate and behavior, then tendtowards a common base class. If allthey share is a set of methodsignatures, then tend towards aninterface.
Homogeneity
If all the variousimplementations share is themethod signatures, then aninterface works best.
If the various implementations areall of a kind and share a commonstatus and behavior, usually anabstract class works best.
Maintenance
If your client code talks onlyin terms of an interface, youcan easily change theconcrete implementationbehind it, using a factory
method.
Just like an interface, if your clientcode talks only in terms of anabstract class, you can easilychange the concreteimplementation behind it, using a
factory method.
Speed
Slow, requires extraindirection to find thecorresponding method in theactual class. Modern JVMsare discovering ways toreduce this speed penalty.
Fast
Terseness The constant declarations inan interface are all presumed
You can put shared code into anabstract class, where you cannot
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 81/126
public static final, so youmay leave that part out. Youcan't call any methods tocompute the initial values of your constants. You need notdeclare individual methods of
an interface abstract. Theyare all presumed so.
into an interface. If interfaces wantto share code, you will have towrite other bubblegum to arrangethat. You may use methods tocompute the initial values of yourconstants and variables, bothinstance and static. You mustdeclare all the individual methodsof an abstract class abstract.
Addingfunctionality
If you add a new method toan interface, you must trackdown all implementations of that interface in the universeand provide them with aconcrete implementation of that method.
If you add a new method to anabstract class, you have the optionof providing a defaultimplementation of it. Then allexisting code will continue to workwithout change.
Difference between Object Base and ObjectOriented ?
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 82/126
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:-
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 83/126
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 toperforming 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;
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 84/126
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 conceptas ref keyword, but passing a ref parameter needs variable to be initialized while
out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.
Note: You must assigned value to out parameter in method body, otherwise the
method won’t compiled.
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 85/126
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 86/126
{
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
{
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 87/126
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 providingrelevant 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 88/126
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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 89/126
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:
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 90/126
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 tooperate 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 91/126
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 classAn 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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 92/126
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 won’t 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 93/126
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;
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 94/126
// 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 ina 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 notfrom 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 95/126
{
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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 96/126
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 doesn’t allow to create object for its
derived class, i.e you loose inherent facility for that class.
Example:
Class A
{
// some codePrivate Void A()
{
//Private Constructor
}
}
Class B:A
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 97/126
{
//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)
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 98/126
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 ManagementConcepts:
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;]
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 99/126
[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 objectoriented languages.
• ENCAPSULATION:- Encapsulation provides the ability to hide the internaldetails of an object from its users.The concept of encapsulation is also knownas data hiding or information hiding. In c# , Encapsulation is implementedusing the access modifier keywords.
1. Public2. Private3. protected
4. Internal5. Protected Internal
• POLYMORPHISM:- It is also concept of oops. It is ability to take more thanone form. An operation may exhibit different behaviour in different situations.
EX:- An addition operation involving
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 100/126
two numeric values will produce sum and the same addition operation willproduce a string.If we pass parameter numeric value then method returnsum(numeric value) and if we pass parameter String then same method isreturn string value .this called Polymorphish.
• INHERITANCE:- One class can include the feature of another class by usingthe concept of inheritance.In c# a class can be inherit only from one class ata time.Whenever we create class that automatic inherit from System.Objectclass,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.netC# can access unmanaged code in the backgroundc# has more functionality
Is This Answer Correct ? 26 Yes 21 No
0
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 101/126
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
touse Interface to achieve this.
In C# multiple inheritance is available.
As every code is compiled to byte code in MSIL, it doesnotmake 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 isyours!
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 differencein
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 inVB.Net.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 102/126
3- VB.Net uses WITH KEYWORD, C# does not have WITHKeyword(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 allthe concepts of OOPs. But VB.net is not fully OO languagebecause some of the OOPs features like operator loadingitdoes 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 compileto MSIL, so given the same basic code structure, there isno difference in execution speed. Of course, eitherlanguage may have features that encourage more or lessefficient coding structures in certain circumstances, but
the compiler optimizers usually catch many of these andoptimize them accordingly.
2. VB.NET can indeed do operator overloading with theOperator statement (this may have been added to newerversions such as VS2005 since the previous answers wereposted).
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 designednot to need MI. In all .NET languages including VB.NET,the concept of Interfaces allows a limited form of an MI-like concept. A single Class can Implement multipleInterfaces, but Derive from only one parent Class. It caneven do both in the same Class — again, regardless oflanguage.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 103/126
4. In more modern versions of both languages (C# 2.0 &3.0, VB.NET 9+), LINQ and many supporting technologies toenable and empower LINQ were added. These are verypowerful in their own right as well as enabling the power
of LINQ, and C# does indeed currently have an advantagehere: lambdas are implemented much better in C# than inVB.NET (they can be multiline in C#, one expression onlyin VB.NET, and C# allows void-function [C-type languageequivalent of Subs, namely, doesn’t return a value]lambdas while the current VB.NET 9 still doesn’t allowlambda Subs, only single-expression single-return-valueFunctions), C# allows Automatic Properties (a verypowerful code saver, but useless for technlogies such asWPF that extend the concept of properties [e.g. WPF
Dependency Properties]) while VB.NET doesn’t yet (butwill in .VB.NET 10 / VS2010 / NET Framework 4.0). CodeSnippets mitigate the Automatic Properties thing anyway.Both have Extension Methods, Anonymous Types, etc.
Some items not directly related to OOPS but often missedin discussions like this:
1. C# (like other C-derived languages) has post/preinc/decrementer operators (++, --), plus operate-and-
assign operators (e.g. +=), bitwise shifts (<<, >>),short-circuiting logical operators, the ternary operator(?:), etc. While not widely known among those notfamiliar with it, VB.NET in its latest versions doescurrently have all of those except the post/preinc/decrementers. Much of their functionality can be donewith += or -= ("myCounter += 1" isn't that much harder totype nor convoluted than "myCounter++", but of course thelatter does have the powerful advantage of being usablein expressions).
2. The VB.NET version of the ternary operator (introducedin VB.NET 8 or 9, IIRC) looks like a function, but isnot: If(booleanExpression, trueValue, falseValue) -- thisis not to be confused with the actual IIf(,,) functionavailable all along which looks similar but is not short-circuited and is a function, not an operator.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 104/126
3. VB.NET now provides nullable value types, simply byputting a question mark after the Type ("Dim discount AsDecimal?"). Nullables have a ".HasValue" Booleanproperty, and a read-only ".Value" property. A two-
operand overload of the If() function-like operatorallows for providing a default value in case of a Null(Nothing in VB.NET), similar to the ISNULL function in T-SQL or a two-operand COALESCE function in ANSI standardSQL:
salePrice -= If(discount, 0@) ' If the discount amountis Nothing (null), treat it as 0, avoiding a Null Valueruntime 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 haveexisted since way back when in VB. C# still doesn’t havethem, and must resort to .NET classes. This means thatyou can have date and datetime literals in VB (simplydelimited with “#”), while you have to parse a string orprovide 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 suchcircumstances, if it didn’t, this is one obvious exampleof 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! Norun-time hit!
vs.
DateTime santaDue = DateTime.Parse("12/24/2009 12:59:59PM"); // 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 105/126
parse, but int literals have to be stuffed into date/timeparts at run time), yet still not a pre-compiled literalconstant. Not as intuitive to read, either.
I’d be interested to know if the C# optimizer can
recognize such initializations using string or integerconstants 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 URLhttp://localhost/
If the IIS Welcome page appears IIS is installed andworking properly.
If the Under construction page error appears IIS may(Installed but not configured properly or IIS servicesmight 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-relatedadministration features for configuring ASP.NET. For moreinformation.
In IIS 7.0, the administration of ASP.NET applications isintegrated more closely with IIS administration, andthereis no separate snap-in. Instead, all IIS and ASP.NETconfiguration is done by using IIS Manager. Because IIS7.0
configuration information is based on the .NET Frameworkconfiguration system, the Web.config file for anapplication that runs in IIS 7.0 contains both Web serverand ASP.NET configuration settings.
For example, in a Web.config file for an ASP.NETapplication running in IIS 7.0, you can specify thedefault
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 106/126
file to return when a browser does not request a specificfile.In IIS 6.0 and earlier versions of IIS, this was asetting that was maintained in the IIS metabase.
Re: port no of FTP Answer
# 3 Active FTP:Command Port - 21Data Port - 20
Re: portno for HTTP & HTTPS Answer
# 2
HTTP - 80HTTPS - 443
Re: How do you create Virtual Root in IIS? Answer# 1
just simple.FIRST CREATE THE NEWFOLDER IN THE ANY OF THE URSYSTEM,THATIS THE UR ORIGINAL ROOT FOLDER.goto
start-->run--.type INETMGR--->GOTO DEFAULTWEBSITE-->RIGHTCLICK-->GOTO NEW-->SELECT NEW VIRTUALDIRECTORY-->GIVE THE ALIAS NAME OF THE ROOT->CLICK
NEXT-->GIVE YHE PATH OF THE ORIGINAL DIRECTORY-->CLICKNEXT--> 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 IISmanager, go to the site for which you need to create thevirtual root [ virtual directory] Browse to that folderunder the site, right click > properties > and Selectcreateapplication.
Where are the IIS log files stored? Answer
# 1 To determine where your IIS log files are stored, please
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 107/126
execute the steps below on your server:
1. Go to Start -> run2. type inetmgr
3. Find your web site under the tree on the leftandright-click on it.
4. Choose properties
5. On the Web Site tab, you should see an optionnearthe bottom that says "Active Log Format." Next to it isa
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 andthe log file name. The full log path is comprised of thelog file directory plus the first part of the log filename. For example, take the following case.
1. Log file directory: C:\Windows\System32\LogFiles
2. Log file name: W3SVC1\exyymmdd.log
3. Your full log path to put into SmarterStatswouldbe: 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 isC:\windows\system32\LogFiles\W3SVC1.we can change this to any specific location.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 108/126
What are different authentication types. How do you retreive user id in case of windows
authentication. Answer
# 1
1.Window2. 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 orKerberose, AuthType in IIS metabase)Basic Authentication – ( Clear Text )Digest AuthenticationAdvance Digest AuthenticationWindows Form based authentication (using database at theblackened)IIS 6 includes. Passport Authentication.I believe Radius Authentication is one which can beincluded..! Authentication with Internet Authenticationservice IAS.
How do you retrive UserID in case of WindowsAuthentication?
HTTP header has the property Auth_Type = Theauthenticationmethod that the server uses to validate users ( NTLM orKerberos if Windows Intergrated Authenticaiton is used)
AUTH_USER = Returns the raw authenticated user name
Create a ASP page on webserver and drop the followinglinesto see the auth user..!:)
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 109/126
<%for each x in Request.ServerVariablesresponse.write(x & "<br />")
next%>
What are different authentication types. How do you retreive user id in case of windows
authentication. Answer
# 3
Windows integrated authenticationAnonymous 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 singleworker process. But An application pool with multipleworker 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 anoption for limiting the Request Queue going to Kernel.
If it is set as 1000 and if the kernel receives 1500requests, then the worker process fails of over loading.
In order to avoid that 2 or more worker processes areassigned 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 propertiesPerformance tab. There you can assign the number ofworkerprocesses for an application pool.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 110/126
Re: What is the difference between connected environment and a disconnected environment?
Answer
# 1
In connected,an application is constantly connected todata
source.advantages :data concurrency is avoided because one user is
connectedto a data source and updating data,while another usercantmade changes on data.In disconnected environment ,application isnt directlyconnected to data source.user use connection at once toretrieve 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 isconstantly opened to operate on the databases, and isclosedafter all the operation are performed.Advantages: fast retrieval of data, updated informationisalways accessedDisadvantage: security threats
Disconnected:In the disconnected environment, the connection object isopened for the minimum amount of time, that is, the timewhen data is retrieved. After the data is retrieved fromthedatabase, the connection is closed, and all theoperationslike INSERT, UPDATE, DELETE, etc are performed offline.The
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 111/126
change during the operation can be reflected back to thedatabase in the similar manner.Advantage: no security threats, increase in performanceasconnection is not constantly opened.
Disadvantage: slow data retrival.: How to insert multiple records in asp .net from Gridview to Sql Database with out using loopcondition ? Answer
# 1
It is possible to insert many records and just save it toDBwithout 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 XMLformat 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 sessionb/wthe pages.Stored Procedure use for Database communication...For Example: add,remove,update etc any record fromdatabase.
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
oneor more tables. Though it is similar to a table, it isstored in the database. It is a query stored as anobject.Hence, a view is an object that derives its data from oneormore tables. These tables are referred to as base or
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 112/126
underlying tables.
Once you have defined a view, you can reference it likeanyother 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 codethat you save so you can reuse the code over and overagain.
So if you think about a query that you write over andoveragain, instead of having to write that query each timeyouwould save it as a stored procedure and then just callthestored procedure to execute the SQL code that you savedaspart of the stored procedure.
Re: what is type dataset? Answer
# 1 Dataset is collection of datatables.the collectiongeneralyrepresented as *)tables-rows-columns-constraintsDataSet 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 113/126
When We create dataset programmely taht is weak type dataset.like DataSet ds=new DataSet();
But when We Create a DataSet using XML Schema(Xsd) thatis called strong type data set that has extension .xsdand 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 hasanassociated XML schema, which is created at the time ofcreation of the datset.An Untyped dataset does not have any associated XML
shema.Inan untyped dataset,the tables and columns are representedascollections.Because an XML shema is not created for anuntyped datset,the structure of an untyped dataset is notknown 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 methodRe: 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 getfilled in the same default datatable of the dataset.That is, when we fill dataset with one adapter, thecontentsgot filled in the table, and when we fill the samedatasetagain 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 dothis,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.
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 114/126
Re: Differentiate between Dataset and Recordset. Answer
# 1
Similar to the DataSet, a Recordset could be disconnectedfromits data store and therefore act as an in-memory cache of
data. Of course, it could also be used in a connectedmodeldepending on the cursor options that were set. AlthoughtheRecordset object stored multiple versions of each columnforeach of its rows, it was not by nature able to representmultiple tables without the use of the Data ShapeProvider.The Recordset was not XML-based and could not be
serialized toXML easily or flexibly. Finally, a Recordset was notindependent of a data store because it tracked aConnectionobject and through its methods could send queries to thedatasource to populate, update, and refresh its data. To thatend,the Recordset contained functionality found in theADO.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 likeoracle and SQL Server and manage them in one dataset,with
recordset this is not possible.
2) All representation of Dataset is using XML whilerecordset uses COM.
Re: How to fetch the last inserted record in a particular table? Answer
# 1
CommanObject.CommandText="Select @@Identity";
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 115/126
** Note: Over a given connection if any insert statementisexecuted on a table with identity column , the back endsql-server for the connection initializes a parameter byname "@@Identity" with the value of Identity column for
thelast inserted record.Re: How to fetch the last inserted record in a particular table? Answer
# 2
By using scope_identityRe: 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 statementisexecuted on a table with identity column , the back endsql-server for the connection initializes a parameter byname "@@Identity" with the value of Identity column forthelast 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 lastinserted 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 scomplete query fr last inserted record fetch from table
select * from <tablename> where id=(select max(id)from <table name>)
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 116/126
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 likeSELECT 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:
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 117/126
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 inSQL2005 Database... Answer
# 1
Using Dataset first create data row thendr[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 databaseRe: 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 integersqlcommand cmd=new sqlcommand("insert into tablenamevalues("+convert.toint32(radiobutton1.selecteditem.text)+"",con);
Is This Answer Correct ? 4 Yes 4 No
0Lalitkumar
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.Youneed 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 insertin SQL2005 Database... Answer
# 5
If(Radiobutton.checked == true){string str1 = "Male";
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 118/126
}
insert into #t value(str1);
Is This Answer Correct ? 6 Yes 0 No
0Vinay 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. Theapplication can use ado.net to connect to data sources toretrieve, manipulate and update data.
Is This Answer Correct ? 15 Yes 1 No
0
Mithun
Re: what is ado.net Answer
# 2 ado.net is collection of managed providers that providescommunication 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 databaseat runtime. We can do the operations which are related tothe database..
Is This Answer Correct ? 8 Yes 0 No0
Archana
Re: what is ado.net Answer
# 4
It is a part of the base class library that is includedwith the Microsoft .NET Framework. It is commonly used by
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 119/126
programmers to access and modify data stored inrelationaldatabase systems, though it can also access data in non-relational sources
Is This Answer Correct ? 4 Yes 1 No0
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 accessservice to .net programmer
Is This Answer Correct ? 2 Yes 1 No
0Narra.rajeevreddy Re: what is ado.net Answer
# 6
ADO.NET is the technology that is used to access thedatabase 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
1Naren
Re: IF we have lot of records in Database. How we can handle them? Answer
# 2
You can handle Large data by practicing some designpatterns like, using stored procedures rather thanStatements, Use coloum names rather tahn * when fetchingthe 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, tochange the timeout for one specific page:
<location path="somefile.aspx"><system.web>
<httpRuntime executionTimeout="180"/></system.web>
</location>
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 120/126
Hope that helps.
Ashish Bharadwaj,Noida(delhi)mail:[email protected]
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 fastlywe must use Triggers ,Stored procedure to maintain
accuracy ,and Indexing for fast retrival of dataRe: What is the main difference between ADO and ADO.Net Answer
# 1
ADO- Connection-Oriented ArchitectureUse Record SetCommunicate in Binary mode
Ado.net Dis-connected architectureUse DataSet,AdapterParse 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 thatwhena connection to the database is made, the connectionremainsopen until the application is closed.
ADO.NET is disconnected database access model, whichmeanswhen an application interacts with the database, theconnection is opened to serve the request of theapplication, and is closed as soon as the request iscompleted.
All data is presented in XML, as compared to ADO.Re: What is the main difference between ADO and ADO.Net Answer
# 3
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 121/126
The old ADO (ActiveX Data Object) has evolved to ADO.NETinthe .NET Framework. The ADO.NET object is a lightweightobject. The ADO Recordset was a huge object in ADO. Itprovided the ability to support multiple types of
cursors.It provided fast lightweight "firehose" cursor and alsosupported a disconnected client-side cursor thatsupportedtracking, optimistic locking, and automatic batch updatesofa central database. However, all of this functionalitywasdifficult to customize.ADO.NET breaks the functionality of the ADO object to
multiple classes, thereby allowing a focused approach todeveloping code. The ADO.NET DataReader is equivalent tothe"firehose" cursor. The DataSet is a disconnected cachewithtracking and control binding functionality. TheDataAdapterprovides the ability to completely customize how thecentraldata 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 ArchitectureUse Record SetCommunicate in Binary mode
Ado.net Dis-connected architectureUse DataSet,AdapterParse Data in XML mode
Re: How to sort the data in Datatable Answer
# 1 pass the datatable in dataview object and call the sortmethod on dataviewdataview dv=new dataview(dt)dv.sortthat's it
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 122/126
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","Sortexpression");
Here Sort expression is , for eg.Address is one of thefield in dt.
Then DataRow[] dr=dt.Select("","Address ASC");
But in this method is have the Datarow array.So you canuse
another one method,I explain below.
DataView dv=new DataView(Datatable,Filter Exp,SortExp,Dataviewrowstate)
Eg is
DataView dv=new DataView(dt,"","AddressASC,DataViewVowState.CurrentRows);
Here we can copy this Dataview to datatable or use thissame 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 database1 -> data reader2 -> data adapter
when you use datareadercreate connection object and open the connectionSqlCommand cmd = new SqlCommand(sql,con);cmd.CommandType = CommandType.Text;SqlDataReader sread = cmd.ExecuteReader();while(sread.Read()){
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 123/126
String data1 = sread.GetString(0);int data2 = sread.GetValue(1);String data3 = sread.GetString(2);
}
when u use the dataadapter
create the connection and openSqlDataAdapter sda = new SqlDataAdapter(sql,con);DataSet ds = new DataSet();sda.Fill(ds,"customer");
then use can get the data in row wise or directly assignthe 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 .net1st we have to create connection object through sqlclientoroledb provider.then open connection2nd We can choose datacommands or data adapter(bysqlclintor oledb dataprovider
system.datasystem.data.oledb //to oledb adaptersystem.data.sqlclient //to sqlclient adapterdim con as new connection
con=("provider=oledb;initialcatalog=databasename;userid=sa;paswd=;datasource=servername;")con.opendim query as string="select* from tabel"dim ad as new oledb.oledbprovider(query,con)
dim ds as datasetad.fill(ds)dim dt as new datatable()dt=ds.table(0) //is for ist tabeldim dr() as datarow //it is array becouse it contain allrows and coulmn for tabledr()=dt.select("") //blank for all coulmns and rows
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 124/126
for i as integer=0 to dr.length-1.tostringif 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
thetextbox text in listbox.suppose u enter a001 if it isvalideid then the all records of a001 r added into the list
box.//next
it will work fine.try thanksRe: Write steps of retrieving data using ado.net ? Answer
# 3
Take a gridview control in ur designaddusing 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
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 125/126
Why Architecture is important?
The primary goal of software architecture is to define the non-functional
requirements of a system and define the environment. The detailed design is
followed by a definition of how to deliver the functional behavior within the
architectural rules. Architecture is important because it:
• Controls complexity• Enforces best practices• Gives consistency and uniformity• Increases predictability• Enables re-use.
What is the difference between an Interface and an Abstract class?
There are quite a big difference between an interface and an abstract class, even though both
look similar.
o Interface definition begins with a keyword interface so it is of typeinterface
o Abstract classes are declared with the abstract keyword so it is of typeclass
o Interface has no implementation, but they have to be implemented.
o Abstract class’s methods can have implementations and they have tobe extended.o Interfaces can only have method declaration (implicitly public and
abstract) and fields (implicitly public static)o Abstract class’s methods can’t have implementation only when
declared abstract.o Interface can inherit more than one interfaceso Abstract class can implement more than one interfaces, but can inherit
only one class
7/29/2019 use oops
http://slidepdf.com/reader/full/use-oops 126/126
o Abstract class must override all abstract method and may overridevirtual methods
o Interface can be used when the implementation is changingo Abstract class can be used to provide some default behavior for a base
class.o Interface makes implementation interchangeableo Interface increase security by hiding the implementationo Abstract class can be used when implementing frameworko Abstract classes are an excellent way to create planned inheritance
hierarchies and also to use as non-leaf classes in class hierarchies.