Anda di halaman 1dari 74

State management is the process by which you maintain state and page information over

multiple requests for the same or different pages.


Types of State Management
There are 2 types State Management:

1. Client – Side State Management


This stores information on the client's computer by embedding the information into a Web
page, a uniform resource locator(url), or a cookie. The techniques available to store the
state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add
custom values to the view state. It is used by the Asp.net page framework to automatically
save the values of the page and of each control just prior to rendering to the page. When
the page is posted, one of the first tasks performed by page processing is to restore view
state.

b. Control State – If you create a custom control that requires view state to work properly,
you should use control state to ensure other developers don’t break your control by
disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without
displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every
page request to the same server. Cookies are the best way to store state data that must be
available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use
query strings when you want a user to be able to e-mail or instant message state data with
a URL.

2. Server – Side State Management


a. Application State - Application State information is available to all pages, regardless of
which user requests a page.

b. Session State – Session State information is available to all pages opened by a user
during a single visit.

Both application state and session state information is lost when the application restarts. To
persist user data between application restarts, you can store it using profile properties.

Implementation Procedure

Client – Side State Management:

View State:
The ViewState property provides a dictionary object for retaining values between multiple
requests for the same page. When an ASP.NET page is processed, the current state of the
page and controls is hashed into a string and saved in the page as a hidden field. If the data
is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET
2.0) to split it across multiple hidden fields. The following code sample demonstrates how
view state adds data as a hidden form within a Web page’s HTML:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE”
value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2ID
E6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />

Encrypting of the View State: You can enable view state encryption to make it more difficult
for attackers and malicious users to directly read view state information. Though this adds
processing overhead to the Web server, it supports in storing confidential information in
view state. To configure view state encryption for an application does the following:

<Configuration>

<system.web>

<pages viewStateEncryptionMode="Always"/>

</system.web>

</configuration>

Alternatively, you can enable view state encryption for a specific page by setting the value
in the page directive, as the following sample demonstrates:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" ViewStateEncryptionMode="Always"%>

View State is enabled by default, but if you can disable it by setting the EnableViewState
property for each web control to false. This reduces the server processing time and
decreases page size.
Reading and Writing Custom View State Data:
If you have a value that you’d like to keep track of while the user is visiting a single
ASP.NET Web page, adding a custom value to ViewState is the most efficient and secure
way to do that. However, ViewState is lost if the user visits a different Web page, so it is
useful only for temporarily storing values.
Example: Determine the time of last visit to the page

// Check if View State object exists, and display it if it does

If (ViewState ["lastVisit"]!= null)

Label1.Text = (string)ViewState["lastVisit"]; else

Label1.Text = "lastVisit ViewState not defined.";

// Define the ViewState object for the next page view ViewState.Add("lastVisit",
DateTime.Now.ToString());
Control State: If you create a custom control that requires ViewState, you can use the
ControlState property to store state information for your control. ControlState allows you to
persist property information that is specific to a control and cannot be turned off like the
ViewState property. To use control state in a custom control, your control must override the
OnInit method and call the Register-RequiresControlState method during initialization and
then override the SaveControl-State and LoadControlState methods.

Hidden fields: ViewState stores information in the Web page using hidden fields. Hidden
fields are sent back to the server when the user submits a form; however, the information
is never displayed by the Web browser (unless the user chooses to view the page source).
ASP.NET allows you to create your own custom hidden fields and store values that are
submitted with other form data. A HiddenField control stores a single variable in its Value
property and must be explicitly added to the page. You can use hidden fields only to store
information for a single page, so it is not useful for storing session data. If you use hidden
fields, you must submit your pages to the server using Hypertext Transfer Protocol (HTTP)
POST (which happens if the user presses a button) rather than requesting the page using
HTTP GET (which happens if the user clicks a link). Unlike view state data, hidden fields
have no built-in compression, encryption, hashing, or chunking, so users can view or modify
data stored in hidden fields.

Cookies: Web applications can store small pieces of data in the client’s Web browser by
using cookies. A cookie is a small amount of data that is stored either in a text file on the
client file system (if the cookie is persistent) or in memory in the client browser session (if
the cookie is temporary). The most common use of cookies is to identify a single user as he
or she visits multiple Web pages.

Reading and Writing Cookies:


A Web application creates a cookie by sending it to the client as a header in an HTTP
response. The Web browser then submits the same cookie to the server with every new
request.
Create a cookie -> add a value to the Response.Cookies HttpCookieCollection.
Read a cookie -> read values in Request.Cookies.
Example:
// Check if cookie exists, and display it if it does

if (Request.Cookies["lastVisit"] != null) // Encode the cookie in case the cookie contains


client-side script Label1.Text = Server.HtmlEncode(Request.Cookies["lastVisit"].Value);

else Label1.Text = "No value defined";

// Define the cookie for the next visit Response.Cookies["lastVisit"].Value =


DateTime.Now.ToString();Response.Cookies["lastVisit"].Expires =
DateTime.Now.AddDays(1);

If you do not define the Expires property, the browser stores it in memory and the cookie is
lost if the user closes his or her browser.

To delete a cookie, overwrite the cookie and set an expiration date in the past. You can’t
directly delete cookies because they are stored on the client’s computer.
Controlling the Cookie Scope: By default, browsers won’t send a cookie to a Web site with a
different hostname. You can control a cookie’s scope to either limit the scope to a specific
folder on the Web server or expand the scope to any server in a domain. To limit the scope
of a cookie to a folder, set the Path property, as the following example demonstrates:

Example:
Response.Cookies["lastVisit"].Path = "/Application1";

Through this the scope is limited to the “/Application1” folder that is the browser submits
the cookie to any page with in this folder and not to pages in other folders even if the folder
is in the same server. We can expand the scope to a particular domain using the following
statement:
Example:
Response.Cookies[“lastVisit”].Domain = “Contoso”;

Storing Multiple Values in a Cookie:


Though it depends on the browser, you typically can’t store more than 20 cookies per site,
and each cookie can be a maximum of 4 KB in length. To work around the 20-cookie limit,
you can store multiple values in a cookie, as the following code demonstrates:
Example:

Response.Cookies["info"]["visit"].Value = DateTime.Now.ToString();

Response.Cookies["info"]["firstName"].Value = "Tony";

Response.Cookies["info"]["border"].Value = "blue";

Response.Cookies["info"].Expires = DateTime.Now.AddDays(1);

Running the code in this example sends a cookie with the following value to the Web
browser:
(visit=4/5/2006 2:35:18 PM) (firstName=Tony) (border=blue)

Query Strings: Query strings are commonly used to store variables that identify specific
pages, such as search terms or page numbers. A query string is information that is
appended to the end of a page URL. A typical query string might look like the following real-
world example:
http://support.microsoft.com/Default.aspx?kbid=315233
In this example, the URL identifies the Default.aspx page. The query string (which starts
with a question mark [?]) contains a single parameter named “kbid,” and a value for that
parameter, “315233.” Query strings can also have multiple parameters, such as the
following real-world URL, which specifies a language and query when searching the
Microsoft.com Web site:
http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=hello+world

Value Name | ASP.NET Object | Value


mkt | Request.QueryString[“mkt”] | en-US
setlang | Request.QueryString[“setlang”] | en-US
q | Request.QueryString[“q”] | hello world

Limitations for Query Strings:


1. Some Browsers and client devices impose a 2083 – character limit on the length of the
URL.
2. You must submit the page using an HTTP GET command in order for query string values
to be available during page processing. Therefore, you shouldn’t add query strings to button
targets in forms.
3. You must manually add query string values to every hyperlink that the user might click.
Example:
Label1.Text = "User: " + Server.HtmlEncode(Request.QueryString["user"]) +

", Prefs: " + Server.HtmlEncode(Request.QueryString["prefs"]) +

", Page: " + Server.HtmlEncode(Request.QueryString["page"]);

Server - Side State Management:

Application State: ASP.NET allows you to save values using application state, a global
storage mechanism that is accessible from all pages in the Web application. Application
state is stored in the Application key/value dictionary. Once you add your application-
specific information to application state, the server manages it, and it is never exposed to
the client. Application state is a great place to store information that is not user-specific. By
storing it in the application state, all pages can access data from a single location in
memory, rather than keeping separate copies of the data. Data stored in the Application
object is not permanent and is lost any time the application is restarted.

ASP.NET provides three events that enable you to initialize Application variables (free
resources when the application shuts down) and respond to Application errors:

a. Application_Start: Raised when the application starts. This is the perfect place to initialize
Application variables.

b. Application_End: Raised when an application shuts down. Use this to free application
resources and perform logging.

c. Application_Error: Raised when an unhandled error occurs. Use this to perform error
logging.

Session State: ASP.NET allows you to save values using session state, a storage
mechanism that is accessible from all pages requested by a single Web browser session.
Therefore, you can use session state to store user-specific information. Session state is
similar to application state, except that it is scoped to the current browser session. If
different users are using your application, each user session has a different session state. In
addition, if a user leaves your application and then returns later after the session timeout
period, session state information is lost and a new session is created for the user. Session
state is stored in the Session key/value dictionary.

You can use session state to accomplish the following tasks:


i. Uniquely identify browser or client-device requests and map them to individual session
instances on the server. This allows you to track which pages a user saw on your site during
a specific visit.

ii. Store session-specific data on the server for use across multiple browser or client-device
requests during the same session. This is perfect for storing shopping cart information.

iii. Raise appropriate session management events. In addition, you can write application
code leveraging these events.

ASP.NET session state supports several different storage options for session data:

a. InProc Stores session state in memory on the Web server. This is the default, and it
offers much better performance than using the ASP.NET state service or storing state
information in a database server. InProc is fine for simple applications, but robust
applications that use multiple Web servers or must persist session data between application
restarts should use State Server or SQLServer.

b. StateServer Stores session state in a service called the ASP.NET State Service. This
ensures that session state is preserved if the Web application is restarted and also makes
session state available to multiple Web servers in a Web farm. ASP.NET State Service is
included with any computer set up to run ASP.NET Web applications; however, the service is
set up to start manually by default. Therefore, when configuring the ASP.NET State Service,
you must set the startup type to Automatic.

c. SQLServer Stores session state in a SQL Server database. This ensures that session state
is preserved if the Web application is restarted and also makes session state available to
multiple Web servers in a Web farm. On the same hardware, the ASP.NET State Service
outperforms SQLServer. However, a SQL Server database offers more robust data integrity
and reporting capabilities.

d. Custom Enables you to specify a custom storage provider. You also need to implement
the custom storage provider.

e. Off Disables session state. You should disable session state if you are not using it to
improve performance.

Advantages

Advantages of Client – Side State Management:

1. Better Scalability: With server-side state management, each client that connects to the
Web server consumes memory on the Web server. If a Web site has hundreds or thousands
of simultaneous users, the memory consumed by storing state management information can
become a limiting factor. Pushing this burden to the clients removes that potential
bottleneck.

2. Supports multiple Web servers: With client-side state management, you can distribute
incoming requests across multiple Web servers with no changes to your application because
the client provides all the information the Web server needs to process the request. With
server-side state management, if a client switches servers in the middle of the session, the
new server does not necessarily have access to the client’s state information. You can use
multiple servers with server-side state management, but you need either intelligent load-
balancing (to always forward requests from a client to the same server) or centralized state
management (where state is stored in a central database that all Web servers access).

Advantages of Server – Side State Management:

1. Better security: Client-side state management information can be captured (either in


transit or while it is stored on the client) or maliciously modified. Therefore, you should
never use client-side state management to store confidential information, such as a
password, authorization level, or authentication status.

2. Reduced bandwidth: If you store large amounts of state management information,


sending that information back and forth to the client can increase bandwidth utilization and
page load times, potentially increasing your costs and reducing scalability. The increased
bandwidth usage affects mobile clients most of all, because they often have very slow
connections. Instead, you should store large amounts of state management data (say, more
than 1 KB) on the server.

What is Access Modifier?

Access modifiers determine the extent to which a variable or method can be accessed from
another class or object

The following five accessibility levels can be specified using the access modifiers

• Private
• Protected
• Internal
• Protected internal
• Public

1. What is Private access modifier?

In OOP Attributes, Methods, Properties, Constructors declared with “private” access modifier
get access or visible only to members of current class

For e.g.: Let’s take class BankDetail with access modifier “private”

class BankDetail
{

private string _employeename;


private int _accountnumber;
private double _balanceamount;

private string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
private int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}

private double BalanceAmount


{
set { _balanceamount = value; }
get { return _balanceamount; }
}

private void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename + "Account Number " +
_accountnumber
+ " with Balance Amount is " + _balanceamount);
}

}
Create another class “clsShowDetails”

Now inside class “clsShowDetails” create object of class BankDetail

BankDetail objBank = new BankDetail();


Fron Object objBank if we are trying to access methods,properties of class BankDetail we
cannot access them due to the protction level of “private” access modifier

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class “clsShowDetail”
public void getDetails()
{
objBank.DisplayDetail();
}
We will get error message

(BankDetail.DisplayDetail() is inaccessible due to protection level)


This means we cannot access Attributes, Methods, Properties, Constructors declared with
“private” access modifier outside of class but can get access or visible only to members of
current class

2. What is protected access modifier?

In OOP Attributes, Methods, Properties, Constructors declared with “protected” access


modifier get access or visible only to members of current class as well as to members of
derived class.

For e.g.: Let’s take class BankDetail with access modifier “protected”

class BankDetail
{

protected string _employeename;


protected int _accountnumber;
protected double _balanceamount;

protected string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
protected int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}
protected double BalanceAmount
{
set { _balanceamount = value; }
get { return _balanceamount; }
}
protected void DisplayDetail()
{
Console.WriteLine("BankDetail for " + _employeename + "Account Number " +
_accountnumber
+ " with Balance Amount is " + _balanceamount);
}
}
Create another class “clsShowDetails”

Now inside class “clsShowDetails” create object of class BankDetail

BankDetail objBank = new BankDetail();

public class clsShowDetails:BankDetail


{

public void getDetails()


{
DisplayDetail();
}

}
From class “clsShowDetail”

public void getDetails()


{
DisplayDetail();
}
We will get no error message

This means we can access Attributes, Methods, Properties, Constructors declared with
“protected” access modifier in derived class

3. What is internal access modifier?

In OOP Attributes, Methods, Properties, Constructors declared with “internal” access


modifier get access or visible only to members of current project or in current namespace

For e.g.: Let’s take class BankDetail with access modifier “internal”

class BankDetail
{

internal string _employeename;


internal int _accountnumber;
internal double _balanceamount;

internal string EmployeeName


{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}

internal int AccountNumer


{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}

internal double BalanceAmount


{
set { _balanceamount = value; }
get { return _balanceamount; }
}

internal void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename + "Account Number " +
_accountnumber
+ " with Balance Amount is " + _balanceamount);
}
}
Add New Item in the same project

Create another class “clsShowDetails” in Class2.cs file

Now inside class “clsShowDetails” create object of class BankDetail

BankDetail objBank = new BankDetail();


public class clsShowDetails
{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

From class “clsShowDetails”


public void getDetails()
{
DisplayDetail();
}
We will get no error message

This means we can access Attributes, Methods, Properties, and Constructors declared with
“internal” access or visible only to members of current project or in current namespace

4. What is protected internal access modifier?

In OOP Attributes, Methods, Properties, Constructors declared with “protected internal”


access modifier get access or visible only to members of current project or in current
namespace and also to members of derived class

5. What is public access modifier?

In OOP Attributes, Methods, Properties, Constructors declared with “public” access modifier
get access or visible to all members of classes and projects

class BankDetail
{
public string _employeename;
public int _accountnumber;
public double _balanceamount;
public string EmployeeName
{
set
{
_employeename = value;
}
get
{
return _employeename;
}
}
public int AccountNumer
{
set
{
_accountnumber = value;
}
get { return _accountnumber; }
}
public double BalanceAmount
{
set { _balanceamount = value; }
get { return _balanceamount; }
}

public void DisplayDetail()


{
Console.WriteLine("BankDetail for " + _employeename + "Account Number " +
_accountnumber
+ " with Balance Amount is " + _balanceamount);
}

}
Create another class “clsShowDetails”

Now inside class “clsShowDetails” create object of class BankDetail

BankDetail objBank = new BankDetail();

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class “clsShowDetail”

public void getDetails()


{
objBank.DisplayDetail();
}
We will get no error message

Let’s try to access “public” access modifier with another example

Add New Item in the same project


Create another class “clsShowDetails”

Now inside class “clsShowDetails” create object of class BankDetail

BankDetail objBank = new BankDetail();

public class clsShowDetails


{
BankDetail objBank = new BankDetail();

public void getDetails()


{
objBank.DisplayDetail();
}

}
From class “clsShowDetail”
public void getDetails()
{
objBank.DisplayDetail();
}
We will get no error message

This means “public” access modifier is access or visible to all members of classes and
projects.

When does GarbageCollector runs ?


Posted by: Chvrsri
Garbage Collector runs :

1. When the system has low physical memory


2. Acceptable memory heap is increased.
3. GC.Collect method is called.

What is an Abstraction?
• Abstraction is thinking about something a certain way
• Abstraction is the representation of only the essential features of an object and hiding un
essential features of an object.
• Through Abstraction all relevant data can be hide in order to reduce complexity and
increase efficiency
• Abstraction is simplifying complex reality by modeling classes appropriate to the problem
• Abstraction-outer layout, used in terms of design
• Encapsulation protects abstraction.
• It taking required data and hiding the unwanted data.
In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car.

Abstraction shows only required data and hides unwanted data.

Difference between Encapsulation and Abstraction


1. Abstraction solves the problem in the 1. Encapsulation solves the problem in the
design level implementation level

2. Encapsulation means hiding the code and data in


2. Abstraction is used for hiding the
to a single unit to protect the data from outside
unwanted data and giving relevant data
world

3. Abstraction is a technique that helps to 3. Encapsulation is the technique for packaging the
identify which specific information should information in such a way as to hide what should
be visible and which information should be hidden, and make visible what is intended to be
be hidden. visible.

In this above example abstraction shows only necessary details of car or shows only
necessary details to drive a car like rear view mirror, gear, clutch, steering And hides
internal detail of car like Piston, crankshaft, carburetors, gas turbines etc which is
encapsulation for a car

Abstraction shows only required data and hides unwanted data .

In above example which shows encapsulated detail of a car which is not necessary to
expose to outside world and make visible what is intended to be visible.

What is Polymorphism?

• Polymorphism is one of the primary characteristics (concept) of object-oriented


programming.
• Poly means many and morph means form. Thus, polymorphism refers to being able
to use many forms of a type without regard to the details.
• Polymorphism is the characteristic of being able to assign a different meaning
specifically, to allow an entity such as a variable, a function, or an object to have
more than one form.
• Polymorphism is the ability to process objects differently depending on their data
types.
• Polymorphism is the ability to redefine methods for derived classes.

Types of Polymorphism

• Compile time Polymorphism


• Run time Polymorphism
Compile time Polymorphism
• Compile time Polymorphism also known as method overloading
• Method overloading means having two or more methods with the same name but
with different signatures

Example of Compile time polymorphism

Run time Polymorphism


• Run time Polymorphism also known as method overriding
• Method overriding means having two or more methods with the same name , same
signature but with different implementation

Example of Run time Polymorphism


You can find source code at the top of this article.

What is Encapsulation?

• Encapsulation is one of the fundamental principles of object-oriented programming.


• Encapsulation is a process of hiding all the internal details of an object from the
outside world
• Encapsulation is the ability to hide its data and methods from outside the world and
only expose data and methods that are required
• Encapsulation is a protective barrier that prevents the code and data being randomly
accessed by other code or by outside the class
• Encapsulation gives us maintainability, flexibility and extensibility to our code.
• Encapsulation makes implementation inaccessible to other parts of the program and
protect from whatever actions might be taken outside the function or class.
• Encapsulation provides a way to protect data from accidental corruption
• Encapsulation hides information within an object
• Encapsulation is the technique or process of making the fields in a class private and
providing access to the fields using public methods
• Encapsulation gives you the ability to validate the values before the object user
change or obtain the value
• Encapsulation allows us to create a "black box" and protects an objects internal state
from corruption by its clients.

Two ways to create a validation process.

• Using Accessors and Mutators


• Using properties
In this example _employeeid and _salary is private fields and providing access to the fields
using public methods (SetEmployeeID,GetEmployeeID,SetSalary,GetSalary)
In this example _employeeid and _salary is private fields and providing access to the fields
using public methods (EmployeeID,Salary)

Benefits of Encapsulation

• In Encapsulation fields of a class can be read-only or can be write-only


• A class can have control over in its fields
• A class can change data type of its fields anytime but users of this class do not need
to change any code

Polymorphism
The word Polymorphism means of many forms.In programming this word is meant to reuse
the single code multiple times. In object oriented programming its a big question that why
the Polymorphism is done, what is the purpose of it in our code?

There are lots of people who don't even know the purpose and usage of
Polymorphism.Polymorphism is the 3rd main pillar of OOP without it the object oriented
programming is incomplete. Lets go in the depth of Polymorphism.
Why Polymorphism is done in OOP?

Its obvious that when we do inheritance between two classes, all the methods and
properties of the first class are derived to the other class so that this becomes the child
class which adobes all the functionality of base class.It can also possesses its own separate
methods.

But there is a big problem in inheriting the second class to the first class as it adobes all the
methods same as the base class has,which means that after inheritance both(base class&
child class) have the methods of same name and same body as shown in this example:~

____Base Class___

public class fish


{
public void eat()
{
console.writeline("fish eat");
}
public void swim()
{
console.writeline("fish swim");
}
}

______Derived Class______

class Dolphen:fish
{

public void eat()


{
console.writeline("fish eat");
}
public void swim()
{
console.writeline("fish swim");
}
}

In this example it is clear that when we Inherit two classes, all the methods with the same
name and same body are adobed by the derived class as shown above.Both methods have
the same name but if we change the body of the second method then it makes Compiler
disturb whether to compile base class method or derived class's
method first...

Lets have a look of this code..


____Base Class___

public class fish


{
public void eat()
{
console.writeline("fish eat");
}
public void swim()
{
console.writeline("fish swim");
}
}

______Derived Class______

class Dolphin:fish
{

public void eat()


{
console.writeline("Dolphin can eat");
}
public void swim()
{
console.writeline("Dolphin can swim");
}
}

In this example we have changed the body of the methods of Derived class.Now this will
make the Compiler disturb to compile which method first,because they both have same
name but different bodies.

To remove this problem and to tell the compiler that which method is to be executed we
need to use Polymorphism.

How the Polymorphism is done?

Polymorphism is used to remove the problem which is shown in the above code.It is done
not by changing the name of the methods of both base & derived class.Infect it is done by
adding the "virtual" keyword before the base class method, and the "override" keyword
before the derived class method.As shown in this exmple:

____Base Class___
public class fish
{
public virtual void eat()
{
Console.WriteLine("fish eat");
}
public virtual void swim()
{
Console.WriteLine("fish swim");
}
}

______Derived Class______

class Dolphin : fish


{

public override void eat()


{
Console.WriteLine("Dolphin can eat");
}
public override void swim()
{
Console.WriteLine("Dolphin can swim");
}
}

This is actually the Polymorphism in which we write virtual keyword with the base class
method and we write override keyword with the derived class method as we did. It helps
the compiler to select the method to be executed.

Here is the complete code in which Polymorphism has been applied.

class Program
{
public class fish
{
public virtual void eat()
{ }
public virtual void swim()
{}
public virtual void dive()
{}

}
public class Dolphin : fish
{
public override void eat()
{ Console.WriteLine("Dolphin eats Plants"); }
public override void swim()
{ Console.WriteLine("Dolphin swims quickly"); }
public override void dive()
{ Console.WriteLine("Dolphin dive deeply "); }
public void dance()
{ Console.WriteLine("Dolphin can Dance"); }

}
public class Shark : fish
{
public override void eat()
{ Console.WriteLine("Shark eats dead animal"); }
public override void swim()
{ Console.WriteLine("Sharks swim fastest than Dolphin"); }
public override void dive()
{ Console.WriteLine("Sharks Dive deeper than Dolphin"); }

public void kill()


{ Console.WriteLine("Shark kills Others"); }

static void Main(string[] args)


{
Dolphin D = new Dolphin();
D.dance();
D.dive();
D.eat();
D.swim();
Shark S = new Shark();
S.kill();
S.dive();
S.eat();
S.swim();
Console.ReadLine();
}
}

What is Inheritance?

Inheritance, together with encapsulation and polymorphism, is one of the three primary
characteristics (concept) of object-oriented programming Inheritance enables you to create
new classes that reuse, extend, and modify the behavior that is defined in other classes The
Class whose methods and variables are defined is called super class or base class The Class
that inherits methods and variables are defined is called sub class or derived class
Sometimes base class known as generalized class and derived class known as specialized
class Keyword to declare inheritance is “:” (colon) in visual c#.
Benefits of using Inheritance
Once a behavior (method) or property is defined in a super class(base class),that behavior
or property is automatically inherited by all subclasses (derived class). Code reusability
increased through inheritance Inheritance provide a clear model structure which is easy to
understand without much complexity Using inheritance, classes become grouped together in
a hierarchical tree structure Code are easy to manage and divided into parent and child
classes

Example of Inheritance

Types of Inheritance in C#: -

• Implementation Inheritance
• Multiple Inheritances (Interface Inheritance)

Implementation Inheritance
One base class (super class) and one derived class (sub class).
Sample Picture:

Interface Inheritance
An interface looks like a class, but has no implementation. It contains definitions of events,
indexers, methods and properties. An interface inherited by classes An interface inheritance
defined with keyword “interface”. In C# Interface Inheritance also known as multiple
inheritances.
Inheritance Tree Structure:

Code Example

"Implementation inheritance code example" and "Interface inheritance code example"


attached at the top of this article.

Posted by: Tripati_tutu

Compiler converts the program from one computer language to another computer language
that is translating from a higher level language to a lower level language. A compiler has to
cope with any valid syntax in the source language, and generate semantically equivalent
code in the target language.

Translator which translate one language to many other language or else we can say a
translator is usually translating from a high level language to another high level language,
or from a low level language to a high level language. A translator usually has a fixed body
of code that is required to translate the program.
What is an application pool?
Posted by: Prasham

1. An application pool is a set of one or more websites in IIS served by the worker process.

2. Each application pool has its own worker process.

3. This process isolation prevents processing from interfacing with one another.

Define the list of properties, methods and events included in SmtpClient class in
the Framework?
Posted by: Tripati_tutu

Here is some partial list of the members of the SmtpClient class...

1) Properties:
• Host- The name or IP address of your email server.
• Port- The number of the port to use when sending an email message.

2) Methods:
• Send- It enables you to send an email message synchronously
• SendAsync- It enables you to send an email message asynchronously.

3) Events:
• Send Completed- It is raised when an asynchronous send operation completes.

What is the common language runtime (CLR)?

Answer:
The common language runtime (CLR) is major component in the .NET Framework and it is
the execution engine for .NET Framework applications.

It is responsible for proving the number of services, including the following:

1. Code management (loading and execution)

2. Verification of type safety

3. Conversion of Microsoft Intermediate Language (MSIL) to native code

4. Access to metadata (enhanced type information)

5. Managing memory for managed objects

6. Enforcement of code access security (See what is code access security?)


7. Exception handling, including cross-language exceptions

8. Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged
code and data)

9. Automation of object layout

10. Support for developer services (profiling, debugging, and so on)

What is GC in NET Framework?


Answer:
The .NET Framework's garbage collector manages the allocation and release of memory for
your application. Each time you use the new operator to create an object, the runtime
allocates memory for the object from the managed heap. As long as address space is
available in the managed heap, the runtime continues to allocate space for new objects.
However, memory is not infinite. Eventually the garbage collector must perform a collection
in order to free some memory. The garbage collector's optimizing engine determines the
best time to perform a collection, based upon the allocations being made. When the
garbage collector performs a collection, it checks for objects in the managed heap that are
no longer being used by the application and performs the necessary operations to reclaim
their memory.

What is application domain?

Posted by: Poster

The primary purpose of application domain is to isolate an application from other


application. Win32 process provides isolation but in distinct memory address spaces. This is
effective but it is expensive and doesn't scale well. The .NET runtime enforces app domain
isolation by keeping control over the use of memory.

All memory in the app domain is managed by the .net runtime so the runtime can ensure
that app domain do not access each other's memory. Objects in different application
domains communicate either by transporting copies of objects across application domain
boundries or by using a proxy to exchange messages.

What is Satellite Assembly?

Posted by: Raja

It is a often used to deploy language specific resources for an application. These assemblies
work in side-by-side execution because the application has a separate product ID for each
language & installed satellite assemblies in a language specific sub-directory.
When uninstalling, the application removes only the satellite assemblies associated within a
give language & .NET Framework version.

What is MSIL?
Posted by: Raja

MSIL (Microsoft Intermediate Language) is a CPU-Independent instructions set into which


.NET Framework programs are compiled. It contains instructions for loading, storing,
initializing and calling methods on objects.

What is CLS?

Posted by: Raja

CLS (Common Language Specification) is a set of constructs or constraints that serves as a


guide for library writers and compiler writers.It allows libraries to be fully usable from any
language supporting the CLS, and for those languages to integrate with each other. The CLS
is a subset of common type system. The common language specifications is also important
to application developers wh are writing code that will be used by other developers.

What is the diffeernce between Overload and Override?

Posted by: Poster

Overload is the another version of the same function into the class. There can be different
parameters, return type in overload functions (in brief: Same function and different
parameters).

Override is entirely overriding the base class function and creating our own version in the
child class. Base class and child class function name and return type should be same.

What the way to stop a long running thread ?

Posted by: Poster

System.Threading.Thread.Abort

What is multi-threading?

Posted by: Poster

It is basically trying to do more than one thing at a time within a process.

There are two main ways of multi-threading which .NET encourages: starting your own
threads with ThreadStart delegates, and using the ThreadPool class either directly (using
ThreadPool.QueueUserWorkItem) or indirectly using asynchronous methods (such as
Stream.BeginRead, or calling BeginInvoke on any delegate).
What’s difference between System.SystemException and
System.ApplicationException?

Posted by: Poster

The difference between ApplicationException and SystemException is that SystemExceptions


are thrown by the CLR, and ApplicationExceptions are thrown by Applications.

What is CODE Access security?

Posted by: Poster

Code Access Security (CAS), in the Microsoft .NET framework, is Microsoft's solution to
prevent untrusted code from performing privileged actions.

It performs following function

1. Defines permissions and permission sets that represent the right to access various
system resources.
2. Enables administrators to configure security policy by associating sets of permissions with
groups of code (code groups).
3. Enables code to request the permissions it requires in order to run, as well as the
permissions that would be useful to have, and specifies which permissions the code must
never have.
4. Grants permissions to each assembly that is loaded, based on the permissions requested
by the code and on the operations permitted by security policy.
5. Enables code to demand that its callers have specific permissions.
6. Enables code to demand that its callers possess a digital signature, thus allowing only
callers from a particular organization or site to call the protected code.
7. Enforces restrictions on code at run time by comparing the granted permissions of every
caller on the call stack to the permissions that callers must have.

What is Metadata?

Posted by: Poster

Metadata is the complete way of describing what is in a .NET assembly. Digging into the
metadata yields the types available in that assembly, viz. classes, interfaces, enums,
structs, etc., and their containing namespaces, the name of each type, its visibility/scope,
its base class, the interfaces it implemented, its methods and their scope, and each
method’s parameters, type’s properties, and so on.
What is Manifest?

Posted by: Poster

The manifest describes the assembly, providing the logical attributes shared by all the
modules and all components in the assembly. The manifest contains the assembly name,
version number, locale and an optional strong name that uniquely identifying the assembly.

What is the difference between Namespace and Assembly?

Posted by: Poster

Namespace:
1. It is a Collection of names wherein each name is Unique.
2. They form the logical boundary for a Group of classes.
3. Namespace must be specified in Project-Properties.

Assembly:
1. It is an Output Unit. It is a unit of Deployment & a unit of versioning. Assemblies contain
MSIL code.
2. Assemblies are Self-Describing. [e.g. metadata,manifest]
3. An assembly is the primary building block of a .NET Framework application. It is a
collection of functionality that is built, versioned, and deployed as a single implementation
unit (as one or more files). All managed types and resources are marked either as
accessible only within their implementation unit, or by code outside that unit.

What is Managed and Unmanaged code?

Posted by: Poster

Managed Code is what Visual Basic .NET and C# compilers create. It compiles to
Intermediate Language (IL), not to machine code that could run directly on your computer.
The IL is kept in a file called an assembly, along with metadata that describes the classes,
methods, and attributes (such as security requirements) of the code you've created. This
assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to
another server to deploy the assembly there—and often that copying is the only step
required in the deployment.

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released.
Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have
kicking around on your hard drive all produced unmanaged code. It compiled directly to
machine code that ran on the machine where you compiled it—and on other machines as
long as they had the same chip, or nearly the same. It didn't get services such as security
or memory management from an invisible runtime; it got them from the operating system.
And importantly, it got them from the operating system explicitly, by asking for them,
usually by calling an API provided in the Windows SDK. More recent unmanaged
applications got operating system services through COM calls.

For more, see http://www.codeguru.com/columns/Kate/article.php/c4871/

What is JIT (Just-in-time) Compiler ?

Posted by: SheoNarayan

Just-in-time compiler is a compiler used to convert the Commmon Intermediate Language


(CIL) code into native code (also called machine code) that is processed by machine.

A little description

While compiling of .NET program, its code is converted into Common Intermediate
Language code that is done by Common Language Runtime.

But while executing the program this CIL code is converted into Machine code or Native
code that is done by JIT Compiler.

What is the location of Global Assembly Cache on the system.

Posted by: Raja

C:\$WINDOWS\assembly

Can you give an example of when it would be appropriate to use a web service as
opposed to a non-serviced .NET component?

Posted by: Poster

When to use Web Service:


1. Communicating through a Firewall When building a distributed application with
100s/1000s of users spread over multiple locations, there is always the problem of
communicating between client and server because of firewalls and proxy servers. Exposing
your middle tier components as Web Services and invoking the directly from a Windows UI
is a very valid option.

2. Application Integration When integrating applications written in various languages and


running on disparate systems. Or even applications running on the same platform that have
been written by separate vendors.
3. Business-to-Business Integration This is an enabler for B2B intergtation which allows one
to expose vital business processes to authorized supplier and customers. An example would
be exposing electronic ordering and invoicing, allowing customers to send you purchase
orders and suppliers to send you invoices electronically.

4. Software Reuse This takes place at multiple levels. Code Reuse at the Source code level
or binary componet-based resuse. The limiting factor here is that you can reuse the code
but not the data behind it. Webservice overcome this limitation. A scenario could be when
you are building an app that aggregates the functionality of serveral other Applicatons. Each
of these functions could be performed by individual apps, but there is value in perhaps
combining the the multiple apps to present a unifiend view in a Portal or Intranet.

When not to use Web Services:


1. Single machine Applicatons When the apps are running on the same machine and need to
communicate with each other use a native API. You also have the options of using
component technologies such as COM or .NET Componets as there is very little overhead.

2. Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to
communicate to their server counterpart. It is much more efficient to use DCOM in the case
of Win32 apps and .NET Remoting in the case of .NET Apps

What is isPostback property?

Posted by: Lakshmiramesh

. This property is used to check whether the page is being loaded and accessed for the first
time or whether the page is loaded in response to the client postback.
Example:
Consider two combo boxes
In one lets have a list of countries
In the other, the states.
Upon selection of the first, the subsequent one should be populated in accordance. So this
requires postback property in combo boxes to be true.

Explain friend and protected friend?

Posted by: Lakshmiramesh

Friend/Internal - Method, Properties in that class can be accessed by all the classes within
that particular assembly.
Protected Friend/Protected Internal - Methods, Properties can be accessed by the child
classes of that particular class in that particular assembly.
What is the difference between overloading and overriding ? how can this be
.NET?

Posted by: Lakshmiramesh

Overriding - Method has the same signature as the parent class method.
Overloading - Method having diff parameters list or type or the return type may be
different.

Explain serialization?

Posted by: Lakshmiramesh

Serialization is a process of converting an object into a stream of bytes.


.Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer.
Serialization is maily used in the concept of .Net Remoting.

What is a Process, Session and Cookie?

Posted by: Lakshmiramesh

Process - Instance of the application


Session - Instance of the user accessing the application
Cookie - Used for storing small amount of data on client machine.

If cookies is disabled in client browser, will session tracking work?

Posted by: Lakshmiramesh

No, maintaining value in cookie wont be possible. In that case you have to make use of
other ways to maintain state of the data on page.
you can check whether client support cookies or not by using
Request.Browser.Cookies property.

What is web application virtual directory

Posted by: Lakshmiramesh

Virtual directory is the physical location of the application on the machine.


By default it’s - inetpub/wwwroo
Polymorphism code

using System;

using System.Collections.Generic;

class Shapes

public virtual void getArea()

Console.WriteLine("get area formula for different shapes");

public virtual void getVolume()

Console.WriteLine("get volume formula for different shapes");

class Circle : Shapes

public override void getArea()

Console.WriteLine("Area of circle is 3.14 * radius * radius");

class Sphere :Shapes

public override void getArea()

Console.WriteLine("Area of Sphere is 4 * 3.14 * radius * radius");


}

class Prisms :Shapes

public override void getVolume()

Console.WriteLine("Volume of Prisms is breath * height");

class Pyramid : Shapes

public override void getVolume()

Console.WriteLine("Volume of Pyramid is 1/3 breath * height");

class OutPuts

public static void Main()

Shapes objshapes = new Prisms();

objshapes.getVolume();

}
Difference between VB.NET and C#.

Posted by: Syedshakeer

Difference between VB.NET and C#.


VB.NET :
-----------

1)no unsigned int


2)Loosely typed language
3)no operator overloading
4)no pointers
5)no auto XML documentation

C#.net :
-------------
1) supports unsigned int
2)strongly typed language
3)supports operator overloading
4)supports pointers
5)supports auto XML documentation

What are indexers?

Posted by: BABU_AKKANDI

Indexers are similar to properties, except that the get and set accessors of indexers take
parameters, while property accessors do not.

What is Jagged Arrays?

Posted by: BABU_AKKANDI

A jagged array is an array whose elements are arrays. The elements of a jagged array can
be of different dimensions and sizes. A jagged array is sometimes called an "array-of-
arrays."

What is the difference between Array and Arraylist?

Posted by: BABU_AKKANDI


As elements are added to an ArrayList, the capacity is automatically increased as required
through reallocation. The capacity can be decreased by calling TrimToSize or by setting the
Capacity property explicitly.

What is an Interface?

Interface is the collection of abstract method that are implemented in different


applications. It is defined as the process of defining once and use it when and where
we want to implement.

It defines derivation of new classes from more than one super class, that means by using
interface we can implement multiple inheritance.

Interface can not be instantiated but can have reference variable. Interface can contain
only final and static datamembers as well as methods of abstract type, it means the
methods have to be overridden by child.

There is an interface means there must be a child class which has to override all
the methods of interface. If it will not override completely the it should be
abstract class and offers to form concrete class to override.

Syntax to declare interface

interface NAME
{
final static datamembers;
methods;
}

Syntax to declare a child

class CHILD:Interface Class


{
//defination of methods of interface class
}

See the following sample program with one interface and two child implementing the
interface class.

interface Area
{
double Get(double x, double y);
}

class Circle:Area
{
//overriding interface method
public double Get(double x, double y)
{
return 3.14* x * x;
}
}

class Rect:Area
{
//overriding interface method
public double Get(double x, double y)
{
return x * y;
}
}

class InterfaceDemo
{
static void Main(string[] args)
{
//creating objects of child class
Rect r = new Rect();
Circle c = new Circle();
double k = r.Get(10.2, 12.9);
double l = c.Get(5.0,0);
Console.WriteLine("Area of rect= {0}", k);
Console.WriteLine("Area of circle= {0}", l);
}
}

OUTPUT

Area of rect=131.58
Area of circle=78.5

Combining Tables

A query result can include data from multiple tables. To combine data from
multiple tables, you can use the JOIN operation from SQL. The JOIN operation
matches the rows of one table with rows of another table, based on values in
those rows.

Types of JOIN

1. Inner Join
2. Outer Join
Left-Outer Join
Right-Outer Join
Full-Outer Join
3. Cross Join

INNER JOIN

SELECT table1.col, table1.col, table2.col, table2.col FROM table1 INNER JOIN table2 ON
table1.col = table2.col

It is a join that displays only the rows that have a match in both the joined
tables.

This is the default type of join in Query Designer.

Columns containing NULL do not match any values when you are creating an
inner join and are excluded from the result set. NULL values do not match other
NULL values.

LEFT OUTER JOIN

SELECT table1.col, table1.col, table2.col, table2.col FROM table1 LEFT OUTER JOIN table2
ON table1.col = table2.col

It is a join that includes rows even if they do not have related rows in the
joined table.

All rows from the first named table(the "left" table, which appears leftmost in the
JOIN clause) are included. Unmatched rows in the right table do not appear.

For every unmatched record a NULL value will appear for the rightmost table.

RIGHT OUTER JOIN

SELECT table1.col, table1.col, table2.col, table2.col FROM table1 RIGHT OUTER JOIN table2
ON table1.col = table2.col

It is a join that includes rows even if they do not have the related rows in the
joined table.

All the rows from the second-named table(the "right" table, which appears rightmost
in the JOIN clause) are included. Unmatched rows in the left table do not appear.

For every unmatched record a NULL value will appear in the leftmost table.

FULL OUTER JOIN

SELECT table1.col, table1.col, table2.col, table2.col FROM table1 FULL OUTER JOIN table2
ON table1.col = table2.col

It is a join that includes rows even if they do not have related rows in the
joined table.
All rows in all joined tables are included, whether they are matched or not.

For every unmatched record a NULL value will appear for the corresponding
table.

CROSS JOIN

SELECT*FROM table1 CROSS JOIN table2

It is a join whose result set includes one row for each possible pairing of rows from
the two tables.

Trigger

A trigger is a special kind of stored procedure that executes automatically


when a user attempts the specified data modification statement on the specified
table. Miccrosoft SQl server allows the creation of triggers for any given INSERT, UPDATE
or DELETE statement.

Trigger for INSERT

Syntax

CREATE TRIGGER trigger_name ON table_name FOR INSERT AS SQLStatement.

trigger_name:- It is the name of the trigger. A trigger name must confirm to the rules
for identifiers and must be unique within the database.

table_name:- It is the name of the table on which the trigger is executed and is
sometimes called trigger table.

SQLStatement:- The trigger action specified in the Transact-SQL statements go into


effect when INSERT, DELETE or UPDATE operation is attempted.

Example1:-

CREATE TRIGGER ti1 ON Student FOR INSERT AS Print 'Record inserted successfully' // This
will add trigger for insert operation in table student.

Firing a trigger

INSERT Student VALUES("Abhisek", 108)

The output will be,

Record inserted successfully


1 row(s) affected

Example2:-
CREATE TRIGGER ti2 ON Student FOR INSERT AS select*from inserted

Inserted is a logical table and structure is similar to the table on which the
trigger is defined. That is the table on which the user action is attempted, and new values
of the rows that may be changed by the user action.

INSERT Student VALUES("Abinash", 107)

Name Roll
Abinash 107
1 row(s) affected

Trigger for DELETE

Syntax

CREATE TRIGGER trigger_name ON table_name FOR DELETE AS SQLStatement.

Example1

CREATE TRIGGER td1 ON Student FOR DELETE AS 'Record deleted successfully'

This will add a trigger on table student for delete command

DELETE FROM Student WHERE Roll=107

Record inserted successfully


1 row(s) affected

Example2:-

CREATE TRIGGER td2 ON Student FOR DELETE AS select*from deleted

Deleted is a logical table and the structure is similar to the table on which
the trigger is defined. That is, the table on which the user action is attempted, and the
old values of the rows that may be changed by the user action.

DELETE FROM Student WHERE Roll=107

Name Roll
Abinash 107
1 row(s) affected

Trigger for Update

Syntax:-

CREATE TRIGGER trigger_name ON table_name FOR UPDATE AS SQLStatement.

Example1:-
CREATE TRIGGER tu1 ON Student FOR UPDATE AS 'Record updated successfully'

This will add a trigger on table student for delete command

UPDATE Student set Name='Abhisek Panda' whwre roll=108

Record updated successfully


1 row(s) affected

Example2:-

CREATE TRIGGER tu2 ON Student FOR UPDATE AS select*from deleted select*from inserted

Deleted and inserted are logical tables and are structurally similar to the
table on which the trigger is defined. That is, the table on which the user action is
attempted, and hold the old values and new values of the rows that may be changed by the
user action.

UPDATE Student set Name='Abhisek Panda' whwre roll=108

Name Roll
Abhisek 108

Name Roll
Abhisek Panda 108
1 row(s) affected

NB:- First you have to create and execute that trigger and then you have to fire it.

What is an object?

• An object is a software bundle of variables and related methods.

• Objects are related to real life scenario

• Class is the general thing and object is the specialization of general thing

• Objects are instance of classes.

• Declaration of an Object in C#.NET

• ClassName objectName=new ClassName();

• E.g.: Person objPerson= new Person();

An object is characterized by concepts like:

• Attribute

• Behavior

• Identity

1. What is an Attribute?
• Attributes define the characteristics of a class.

• The set of values of an attribute of a particular object is called its state.

• In Class Program attribute can be a string or it can be a integer

Example of Attribute:

2. What is a Behavior?

• Every object has behavior

• In C#, behaviors of objects are written in methods.

• If a behavior of an object needs to be performed, then the corresponding method is


called.

Example of Behavior:
3. What is an Identity?

• Each time an object is created the object identity is been defined.

• This identity is usually created using an identifier which is derived from the type of
item

Example of Identity:
The source code is attached at the top of this article.

sing System;

class SalaryCheque

public string _EmployeeName;

public int _Amount;


public string EmployeeName(string name)

_EmployeeName = name;

return _EmployeeName;

public void EmployeeType(int type)

if (type == 1)

this._Amount = 50000;

if (type == 2)

this._Amount = 27000;

if (type == 3)

this._Amount = 5000;

}
public void DisplayCheque()

Console.WriteLine("This Month Salary for " + _EmployeeName + " is " + _Amount);

class SalaryChequeDisplay

static void Main()

string _name;

int _employeeType;

Console.WriteLine("Please Enter Employee Name");

_name = Console.ReadLine();

Console.WriteLine("Enter Employee type 1 for Manager 2 for Assistant Manager 3


for Worker");

_employeeType = Convert.ToInt16(Console.ReadLine());

SalaryCheque objsal = new SalaryCheque();

objsal.EmployeeName(_name);

objsal.EmployeeType(_employeeType);

objsal.DisplayCheque();
}

Working with Collections - Generic List

Introduction

In my previous article Working with Collections - ArrayList, I briefly described about


ArrayList. In this article I am going to briefly describe about Generic List.

What is the problem?

In order to store ordered list of items (objects), we can simply use an ArrayList, however
there are many disadvantages of using ArrayList particularly when you have a huge number
of objects into it. The most important is every time you need to cast them to get your actual
object and this itself is a big overhead on the application. Also there is no type safety
because you can store a string, an integer as well as a custom class into a single ArrayList
that will not throw any error at compile time but you will get an exception at runtime if you
were intended to store only integer in the ArrayList and were casting for integer object but
someone had added string type of data also.

The best solution in this scenario would be to restrict the type of object you are intended to
store in your collections at the time of declaration itself so that it won't accept any other
type of data.

Generics

The solution of the problem identified above can be solved by using is .NET Generics. In
.NET Framework generic type exist for most of the collection classes, however we will
discuss about generic type of ArrayList in this article. List class is the generic equivalent
of an ArrayList class.

Generic List Class

As an ArrayList is used to add ordered list of object so the List class is. Additionally it is used
to create type-safe ordered list. Lets understand it by an example. Suppose we want to
store only integer value in our collection so we will create List object by specifying the
integer type for the generic parameter. For example

Adding Data into List


Note: You need to use System.Collections.Generic namespace to use .NET Generics.

List<int> list = new List<int>();

list.Add(1);

list.Add(2);
Notice the data type between less than and greather than symbol (<int>), this is how data
type is declared at the time of instantiating List object. In place of int you can use any type
of object, like string, datetime or your custom business objects etc.

When you compile above code it will complie properly. Now lets try to add some string into
it and compile. Notice the 4th line in the below code snippet.

List<int> list = new List<int>();

list.Add(1);

list.Add(2);

list.Add("REA");

If you will try to compile, you will get following error (below picture) as I have passed int as
the generic parameter to the List object and trying to add a string value into it.

If this would have been an ArrayList it would have compiled properly however at run time
while casting this into integer it would have thrown error (as "REA" can't be converted into
integer) .

Interating through List


Iterating through List is almost similar to the ArrayList. Here as we are sure that, we have
passed int as generic parameter to the list so only integer type of data would be there. So
we can simply specify the data type in foreach loop and use them (no need of casting from
object to integer).

// lets see how to iterate through this list

int intTotal = 0;

foreach (int i in list)

intTotal += i;

As against ArrayList, Generic list saves us from any potential exception that may occur at
runtime. As written earlier, List is the generic equivalant of ArrayList so almost all methods
that ArrayList supports (See http://www.dotnetfunda.com/articles/article140.aspx for
ArrayList article) are supported by List. Apart from that there are many overloads and extra
methods also that are very useful.
Useful Resources

There are few articles I came across that are very useful on this topic and I would like to
mention them for the benefits of the readers. Please feel free to respond to this article if you
have some useful resources on this topic.

http://www.ondotnet.com/pub/a/dotnet/2005/06/20/generics.html?page=2
http://www.developer.com/net/net/article.php/11087_3499301_2
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx

Thanks for reading.

Working with Collections - ArrayList

This article describes about ArrayList, its various methods and uses. ArrayList is a simple
and resizable index-based collections of objects. This is a kind of array that is capable of
increase its size dynamically.

Buy proven .NET Trainings on www.ITFunda.Com (Adv)

Introduction

In series of next few articles, I am planning to write about collections. Collections are a
place to store similar or different types of data in an orderly manner. .NET Framework
provide different type of collections for use at different places. Collections classes are the
base of application development because of the utility they provide to the developer.

There are several types of collections in .NET and all these collections classes resides in
System.Collections namespace.

This article describes about ArrayList (Read article on List, Generic equivalent of ArrayList
http://www.dotnetfunda.com/articles/article152.aspx) and where it best fits. ArrayList is a
simple and resizable index-based collections of objects. This is nothing but a kind of array
that is capable of increase its size dynamically. It can store any kind of data that inherit
from System.Object (In .NET all data types are inherited from System.Object so virtually
you can store any type of data into any collections.) ArrayList still uses array type to
implement most of its functionality. ArrayList best fits in the scenario where you don't know
what is the exact size of the items you are going to add in the collections, want to store
variable data irrespective of the data types and your collections are relatively small or
medium size.

Adding items to the ArrayList

Add Method

ArrayList supports two methods of adding items to the collections and these are Add and
AddRange. Add method is used to store any kind of data into the collections, it can either be
string, numeric or any custom objects.
// ArrayList

ArrayList arrayList = new ArrayList();

string lastName = "Narayan";

arrayList.Add("Sheo");

arrayList.Add(lastName);

arrayList.Add(31);

arrayList.Add(new object());

Here you can see that I have added variable, string, numeric or simple object into the
collections. In order to add object into an ArrayList, its not necessary to be of the same
type.

AddRange Method

In addition to Add method, ArrayList also supports AddRange method that is used to add
more than an item into the collection at one go. This is done usually from either an Array or
another collections.

// ArrayList AddRange method

string[] items = new string[] { "Sheo", "Narayan", "Hyderabad", India" };

arrayList.AddRange(items);

AddRange supports adding a range of items from any collections that support ICollection
interface (Infact most of the collections object supports this interface).

Insert and InsertRange method

One important thing to notice here is that Add and ArrayList add items into the collection at
the end of it, what if you want to insert the items in the mid of the collection or at any
specific postions? To do that ArrayList supports Insert and InsertRange methods. These
methods works in the same way as Add and AddRange do but one more parameter you
need to pass into these methods is the postion at which you want to insert the item.

// ArrayList - Insert method

arrayList.Insert(3, "Dutta");

// ArrayList - InsertRange method

int[] insertItems = new int[] { 9, 10, 11 };

arrayList.InsertRange(7, insertItems);

Overwriting an item

If you want to overrite an item already in the ArrayList, you can use the indexers to do that.

// ArraList - Indexers to overwrite item


arrayList[5] = "Overwrite item";

Removing items from ArrayList

The way we added the items into the ArrayList, we can remove the items from ArrayList
using Remove and RemoveRange methods. One additional method is provided by ArrayList
to remove an item is RemoteAt. Lets see them one by one

Remove Method

Remove method is used to remove a item from the collections. But notice that if you are
trying to remove an item that doesn't exist into the collections, ArrayList will not throw any
error, this is cool, isn't it?.

// ArrayList - Remove method

arrayList.Remove(31);

// ArrayList - Remove method, this will not throw any error even if this item doesn't exist in
the collection

arrayList.Remove("Unknown Item");

RemoveAt Method

In case you need to remove an item from a specific location from the ArrayList, you can use
RemoveAt method. In the following example, 4 item from the ArrayList will be removed.

// ArrayList - RemoveAt method

arrayList.RemoveAt(4);

RemoveRange Method

If you want to remove more than one item from the ArrayList at one go, simply use the
RemoveRange method. In this method you need to specify from which index you want to
start with and how many items you want to remove. In following example 6th, 7th, and 8th
item will be removed from the ArrayList as I have specified first parameter from where to
start removing item is 5 (Actually it will be 6th item as collections are 0 based index and its
counting starts from 0) and from there 3 items will be removed.

// ArrayList - RemoveRange method

arrayList.RemoveRange(5, 3);

// Demo of RemoveRange

ArrayList myArrayList = new ArrayList(0);

int[] myInt = new int[] {1, 2, 3, 4, 5};

myArrayList.AddRange(myInt);

// ArrayList - RemoveRange method

myArrayList.RemoveRange(1, 3);
string str = string.Empty;

foreach (int i in myArrayList)

str += i.ToString() + " :";

The output of above code will be 1, 5. As the first parameter is 1, it means the 2nd item ie.
2, and remove 3 items from there ie. 2, 3, 4.

Iterating through items

You must be agree that if we will not have any option to iterate through the items of the
collections and get it back, it will be of hardly any use. ArrayList also provids way to iterate
through the items of the collections and there are many ways to do that.

Using Indexers

ArrayList has a Count property that tells us the size of the collections, we can use them to
loop through the ArryaList.

string str = string.Empty;

for (int i = 0; i < myArrayList.Count; i++)

str += myArrayList[i].ToString() + " :";

Using Enumerators

ArrayList also supports IEnumerable interface that allows us to use enumerators to access
the items of the collections.

string str = string.Empty;

IEnumerator enm = myArrayList.GetEnumerator();

while (enm.MoveNext())

str += enm.Current.ToString() + " :";

Using ForEach loop

ForEach loop is just like enumerators, actually internally it use Enumerators to enumerate
through all the items in the collections. The benefit of using ForEach loop is you can specify
the the data type while looping through the items that saves time in casting from objects
while looping.

// Specifying the data type


foreach (int i in myArrayList)

str += i.ToString() + " :";

// Generic - it will work for all types of object stored in the ArrayList

foreach (object obj in myArrayList)

str += obj.ToString() + " :";

Sorting an ArrayList

ArrayList also supports sorting of the item. To sort the item simply call the Sort method.
This method also takes IComparer object as parameter if you want to use case insensitive
sorting or you want to specify your own comparer class to compare and sort.

// ArrayList - Sort method

arrayList.Sort();

// ArrayList - Sorting, Case insensitive comparsion and sorting

myArrayList.Sort(new CaseInsensitiveComparer());

There are few more methods that are frequently used while working with ArrayList. These
are:

Other Important Methods

Clear Method
Clear method is used to clear all the item from the collections.

myArrayList.Clear();

IndexOf Method

IndexOf method is used to determine if a particular item exists in a collections or not. If an


item exists then it will return the 0 based index of that item otherwise -1.

// will return 1

myArrayList.IndexOf(5);

// Will return -1 as I have removed 2, 3, 4 has been removed from the list
myArrayList.IndexOf(3);

Hope this article will be useful for beginners as well as mid level developers. Please let me
know if you have comments or suggestions. Thanks for reading.

Working with Value Types Variables

This article describes about most of the Value Types variables, its uses and how to use
them.

Buy proven .NET Trainings on www.ITFunda.Com (Adv)

Introduction

Variables are of two types. Reference and Value types. In this article, we are going to cover
Value Types variables. Value types are variables that contain their actual data directly
instead of reference of the data stored elsewhere in the memory. Instances of value types
variables are stored in an area of memory called Stack. Stack is a place where runtime can
create, read, update and remove the data quickly.

Value types variables can be of two types. Build-in and User defined. Lets see each one of
them one by one.

Built-in Value Types Variables

There are many built-in value types variables and we can use them based on our
requirement.

Type Byte Range Used for

sbyte
(System.SByte) 1 -128 to 127 Signed byte values

byte
(System.Byte) 1 0 to 255 Unsigned byte

short
(System.Int16) 2 -32768 to 32767 To store small number
int
(System.Int32) 4 –2147483648 to 2147483647 Whole numbers

uint
(System.UInt32) 4 0 to 4294967295 Only Positive whole nu

long –9223372036854775808 to
(System.Int64) 8 9223372036854770000 Large whole numbers

float
(System.Single) 4 –3.402823E+38 to 3.402823E+38 Floating point number

double –1.79769313486232E+308 to Precise or large floatin


(System.Double) 8 1.79769313486232E+308 numbers

decimal –79228162514264337593543950335 to Financial and scientific


(System.Decimal) 16 79228162514264337593543950335 calculations

Type Byte Range Used for

char
(System.Char) 2 Single unicode charac

Boolean
(System.Boolean) 4 True/False

DateTime 1/1/0001 12:00:00 AM to 12/31/9999


(System.DateTime) 8 11:59:59 PM To store date time

Use of int and uint for variables are recommended as these variables are optimzed by
runtime. For floating point use double for the same reason.

Declaring Value Types Variables

Declaring simple variable


Declaring value types variables are not very tough. You can declare by specifying the name
of the data type like below.

int i = 0;

Here int is the data type of the variable, i is the name of the variable and 0 is the default
value I have used to initialize the variable.

Declaring nullable variables

There are situation where you don't want anything to store in the variable, in that case you
can go ahead with nullable variables.

Nullable<int> i = null;
int? ii = null;

Note that by default you can't assign null to a Value types variables, so if you are planning
to store null in the value types variables, you should declared them as nullable variables.

Now there is a question, how to know whether a nullable variable value has been set or not?
To do that use use following code.

// to detech, use HashValue


if (i.HashValue)
{
// variable value has been set
int i = i.Value; // get the value using i.Value
}

User Defined Types - Struct

User-defined types are also called sructs. According to MSDN, A struct type is a value type
that can contain constructors, constants, fields, methods, properties, indexers, operators,
events, and nested types. As with other value types, instances of user-defined types are
stored on the stack and they contain their data directly. Structures are a composite of other
types that make it easier to work with related data. Structs are used to represent light
weight object. Struct can't inherit a class but it can inherit an interface.

struct Person

public string firstName;

public string lastName;

public Person(string _firstName, string _lastName)

firstName = _firstName;

lastName = _lastName;
}

public override string ToString()

return firstName + " : " + lastName;

To call the above struct, write following code.

Person p = new Person("Sheo", "Narayan");

string myName = p.ToString();

Notice that I have not initialized the firstName and lastName variables in the struct, if you
do so it will throw error at compile time(Person.firstName': cannot have instance field
initializers in structs, in case you are trying to initialize firstName).

Enumerations

Enumerations are group of symbols that have fixed value. The enum keyword is used to
declare an enumeration, a distinct type consisting of a set of named constants called the
enumerator list.

enum tasteType

hot,

sour,

sweet,

salty

to call this enumerations, use following code.

tasteType.hot

Enumerations simplifies the coding by providing limited set of options in readable and
understandable forat to the developers for a particular object.

Conclusion

In this article, we have gone through almost all Value types variables that are generally
used while developing applications. Hope you enjoyed this. Thanks for reading.
Working with Collections - Generic List

This article describes about List class that is generic equivalent of ArrayList class.

Buy proven .NET Trainings on www.ITFunda.Com (Adv)

Introduction

In my previous article Working with Collections - ArrayList, I briefly described about


ArrayList. In this article I am going to briefly describe about Generic List.

What is the problem?

In order to store ordered list of items (objects), we can simply use an ArrayList, however
there are many disadvantages of using ArrayList particularly when you have a huge number
of objects into it. The most important is every time you need to cast them to get your actual
object and this itself is a big overhead on the application. Also there is no type safety
because you can store a string, an integer as well as a custom class into a single ArrayList
that will not throw any error at compile time but you will get an exception at runtime if you
were intended to store only integer in the ArrayList and were casting for integer object but
someone had added string type of data also.

The best solution in this scenario would be to restrict the type of object you are intended to
store in your collections at the time of declaration itself so that it won't accept any other
type of data.

Generics

The solution of the problem identified above can be solved by using is .NET Generics. In
.NET Framework generic type exist for most of the collection classes, however we will
discuss about generic type of ArrayList in this article. List class is the generic equivalent
of an ArrayList class.

Generic List Class

As an ArrayList is used to add ordered list of object so the List class is. Additionally it is used
to create type-safe ordered list. Lets understand it by an example. Suppose we want to
store only integer value in our collection so we will create List object by specifying the
integer type for the generic parameter. For example

Adding Data into List


Note: You need to use System.Collections.Generic namespace to use .NET Generics.

List<int> list = new List<int>();

list.Add(1);

list.Add(2);

Notice the data type between less than and greather than symbol (<int>), this is how data
type is declared at the time of instantiating List object. In place of int you can use any type
of object, like string, datetime or your custom business objects etc.

When you compile above code it will complie properly. Now lets try to add some string into
it and compile. Notice the 4th line in the below code snippet.

List<int> list = new List<int>();

list.Add(1);

list.Add(2);

list.Add("REA");

If you will try to compile, you will get following error (below picture) as I have passed int as
the generic parameter to the List object and trying to add a string value into it.

If this would have been an ArrayList it would have compiled properly however at run time
while casting this into integer it would have thrown error (as "REA" can't be converted into
integer) .

Interating through List


Iterating through List is almost similar to the ArrayList. Here as we are sure that, we have
passed int as generic parameter to the list so only integer type of data would be there. So
we can simply specify the data type in foreach loop and use them (no need of casting from
object to integer).

// lets see how to iterate through this list


int intTotal = 0;

foreach (int i in list)

intTotal += i;

As against ArrayList, Generic list saves us from any potential exception that may occur at
runtime. As written earlier, List is the generic equivalant of ArrayList so almost all methods
that ArrayList supports (See http://www.dotnetfunda.com/articles/article140.aspx for
ArrayList article) are supported by List. Apart from that there are many overloads and extra
methods also that are very useful.

Useful Resources

There are few articles I came across that are very useful on this topic and I would like to
mention them for the benefits of the readers. Please feel free to respond to this article if you
have some useful resources on this topic.

http://www.ondotnet.com/pub/a/dotnet/2005/06/20/generics.html?page=2
http://www.developer.com/net/net/article.php/11087_3499301_2
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx

When to use of DataSet, SqlDataReader and XmlReader

To efficiently write the code of Data Access Layer we must be aware about the
functionality/features of DataSet, SqlDataReader and XmlReader. In this article, I am trying
to describe which objects fits in what scenario.
Buy proven .NET Trainings on www.ITFunda.Com (Adv)

Introduction

When we need to retrive mutliple records from databsae, we have following options
1. DataSet or DataTable - use SqlDataAdapter to generate it
2. SqlDataReader - use it to provide read only, forward only data stream
3. XmlReader - use it to provide a read only, forward only data stream of XML data.

The choice between SqlDataReader and DataSet/DataTable is essentially one of the


performance vs functionality issue. We should use SqlDataReader to gain optimum
performance while DataSet/DataTable gain additional functionality and flexibility.

Use DataSet

We should use a DataSet populated by SqlDataAdapter when

1. We require a disconnected memory-resident cache of data so that we can pass to


different component or layers
2. We are working wtih data retrived from multiple data sources.
3. We want to update some of all retrieved rows using batch updated provided by
SqlDataAdapter
4. We want to perform data binding against a control that requires a data source that spport
IList such as GridView, Repeater etc.

Whenever we are using SqlDataAdapter to generate DataSet or DataTable, following points


should be considered.

1. We don't need to explicitly open or close the database connection as SqlAdapter Fill
method opens the database connection and then closes it before it returns. If the
connection is already open (before using it into SqlDataAdapter) then it leaves it as it is.
2. If we require the connection object to use it further then better to open the connection
before calling Fill method of SqlDataAdapter to avoid reopening it again.

Use SqlDataReader

We should use SqlDataReader by calling ExecuteReader method of SqlCommand object


when

1. We are dealing with large volumes of data - too much to maintain in single cache.
2. We want to reduce the memory occupied by the application (using DataSet consumes
memory)
3. We want to perform data binding with a control that supports a data source that
implements IEnumerable.

When we are using SqlDataReader, following points should be considered.


1. The underlying connection to the database remains open and cannot be used for any
other purpose while the data reader is active. So we should call conn.Close() method as
soon as possible.
2. There can be only one reader per connection.
3. Better to use CommandBehavior.CloseConnection
(dCmd.ExecuteReader(CommandBehavior.CloseConnection)) to close the connection. This
indicates that the connection should be closed when the SqlDataReader is closed.
4. When accessing data by using the reader, use the typed accessor methods like GetInt32,
GetString as they reduce the amound ot type convertion required when reading the column
data.
5. To avoid unnecessary data pulling from the datbase, use Cancel method of Command
object (dCmd.Cancel()) before closing the reader. (lets say you have 100 records into the
reader and after looping through 10 records you think that you got the data you needed
then before closing the reader call Cancel method of the command object) This ensures that
the results are discarded on the server and are not pulled unnecessarily to the client.

Use XmlReader

Use an XmlReader obtained by calling the ExecuteXmlReader method of SqlCommand object


when
1. We want to process the retrieved data as XML but we don't want to incur the overhead of
creating DataSet.

When we are using XmlReader following points should be considered


1. The connection must remain open while we read the data from XmlReader. There is no
support of CommandBehavior.CloseConnection as in case of SqlDataReader so we should
close the connection explicitly.

Conclusion

We generally do these activities on almost all projects, a little attention on what to use
when increases the performance of the overall project and increases the scalability.

Discussing Constructors in C#

In a simple words Constructor is nothing but a method, a special kind of method of a class,
which gets executed when its (class) object is created.

Now, let’s take above in broader sense, a constructor is a class method automatically
executed whenever class’s object is created or whenever class is initialized

Buy proven .NET Trainings on www.ITFunda.Com (Adv)

Introduction

In a simple words Constructor is nothing but a method, a special kind of method of a class,
which gets executed when its (class) object is created.
Now, let’s take above in broader sense, a constructor is a class method automatically execut
ed whenever class’s object is created or whenever class is initialized.

Consider following bit of code:

public class MsDotNetHeaven

public MsDotNetHeaven()

//A default Constructor

//Class members

In above snippet, try to change the name of constructor from MsDotNetHeaven to


MsDotNetMentor and see whats happen, you have to put same name as you gave it to
class.

Behind the scenes:

What happened behind the scenes : whenever you try to create an object of class or
initialize a class, then the default constructor is invoked.

//Initializes the Class

MsDotNetHeaven objMsDnH = new MsDotNetHeaven();

Types of Constructor

This is a n issue of debate but I always like to segregated Constructors in following types:

Default Constructor
A constructor that takes no parameters is called a default constructor. Default constructors
are invoked whenever an object is instantiated by using the new operator and no arguments
are provided to new.

Parameterized Constructor

Besides a default constructor when its need to pass some argument on the initialization of a
class a parameterized constructor is come to picture. It follows the same rules as default
constructor with a difference that it has some parameters which also differentiate it from
default constructor. Go through following snippet:

public class MsDotNetHeaven

public MsDotNetHeaven()

//A default Constructor

public MsDotNetHeaven(String strName)

//A parameterized Constructor having one parameter

public MsDotNetHeaven(String strFirstName, String strLastName)

//A parameterized Constructor having two parameters

//Class members
}

Note:

1. A default constructor should be explicitly declared while declaring parameterized


constructor.

2. Some writer also take Private constructor and Static Constructor as types of
constructor but in my view these are constructor with different modifiers so behave
differ; I will cover these in next section.

Access Modifiers and Prefix with Constructors

By default Constructors are public but we can also use other modifiers and prefix like
private and static. With the use of these modifiers constructors behave differently:

Using Access Modifier private with Constructor

When put private as access modifier to constructor then that constructor is known as
private Constructor

A private constructor is a special instance constructor. It is commonly used in classes that


contain static members only. If a class has one or more private constructors and no public
constructors, then other classes (except nested classes) are not allowed to create instances
of this class.

Some time there is a need where we have not allow outer world to get instantiate our class
then we need to use private modifier with constructor. Consider following piece of code:

public class MsDotNetHeaven

private MsDotNetHeaven()

//A default Constructor as private

//Class members
}

Now whenever you try to invoke following piece of code:

//Initializes the Class

MsDotNetHeaven objMsDnH = new MsDotNetHeaven();

it throws an error: Constructors. MsDotNetHeaven. MsDotNetHeaven ()' is inaccessible due


to its protection level

Now, question comes to mind if the above contains error then what the use is of private
constructor, we can make above class to be initialized by declaring another public
constructor, modify above code-snippet with bellow one:

public class MsDotNetHeaven

private MsDotNetHeaven()

//A default Constructor as private

public MsDotNetHeaven(String strName): this()

//A parameterized Constructor having one parameter

System.Console.WriteLine(“My name is : “ + strName);

//Class members

Now, you can initialize class as follow:

//Initializes the Class

MsDotNetHeaven objMsDnH = new MsDotNetHeaven(“Gaurav Arora”);

Using prefix static with Constructor

With the use of static with constructor gives a name as static constructor

For C++ developers it’s a new concept introduced in C#.


A static constructor is used to initialize any static data, or to perform a particular action that
needs performed once only. It is called automatically before the first instance is created or
any static members are referenced.

Consider the following:

public class MsDotNetHeaven

static MsDotNetHeaven()

//A static Constructor

// Can only access static members here.

System.Console.WriteLine("I am a static constructor.");

//Class members

Now whenever you create an instance of the class MsDotNetHeaven the line I am a static
constructor get printed.

Consider following piece of code:

public class MsDotNetHeaven

static MsDotNetHeaven()

//A static Constructor

// Can only access static members here.

System.Console.WriteLine("I am a static constructor.");

public MsDotNetHeaven()
{

//A default Constructor

//Class members

Above code is perfectly alright and will perform same result as earlier code.

Calling Parent Class Constructors in child class during inheritance

Now, suppose a scenario when you are inheriting a class and want to use Parent class
constructor then how to attain that.

Simple the same has been achieved by using base()

Consider following code-snippet:

public class MsDotNetHeaven

public MsDotNetHeaven()

//A default Constructor

public MsDotNetHeaven(String strName)

//A parameterized Constructor having one parameter

//Class members

public class MsDotNetMentor : MsDotNetHeaven


{

public MsDotNetMentor ()

//A default Constructor

public MsDotNetMentor (String strName) : base(strName)

//A parameterized Constructor having one parameter

//Class members

static void Main()

MsDotNetMentor objMsDnM = new MsDotNetMentor(); //(A)

MsDotNetMentor objNameMsDnM = new MsDotNetMentor(“Gaurav Arora”); //(B)

(A) From above : the sequence of invoking a constructor is first public MsDotNetHeaven()
and then public MsDotNetMentor()

(B) From above : the sequence of invoking a constructor is public MsDotNetHeaven(String


strName)and then public MsDotNetMentor(String strName)

Note:

• A static constructor should not be declared with any access modifier.

• A static constructor does not accept parameters

• A static constructor is called automatically.

• There is no way to call a static constructor directly.


• Can’t stop the execution of Static constructor

Following are the some points to remember :

Important :

• Constructor is nothing but a special method, which initializes the class or its task to
initialize the object of it class.

• Its name must be same as the name of class

• This is a special method as constructors do not have return types, not even void

• Constructor cannot return any value because they didn’t have any return type.

• Constructor can’t be get inherited, although a derived class can class the base class
constructor.

• A class has atleast one constructor also known as default constructor [a constructor
without parameter]

• You have to explicitly write a default constructor while Overloading constructors.

• Concept declaring multiple constructors of a class with different sets of parameters


known as Constructor overloading.

• A constructor can be called another constructor using this()

Anda mungkin juga menyukai