Method Overloading in C

download Method Overloading in C

of 20

Transcript of Method Overloading in C

  • 8/12/2019 Method Overloading in C

    1/20

    Method Overloading in C#We can used more than one Method with same name,within same class but with different

    parameter,that is called method overloading.When the basic functionality of more than one

    method is same but they are used different parameter,then we can implement method

    overloading.

    Method overloading will be possible if method name is same but there signature is different.

    Signature will be different if:-

    1.Number of parameter in method is different.

    EX:-

    show(int x), show(int x,int y),

    here both are same method but number of parameter is different.

    2.Data type of parameter is different.

    EX:-display(int x, int y), display(int x, float y)

    Here both method is same but there parameter is different.

    3.Sequence of data type of parameter is different.

    EX:-

    Display(int x, string y, float z), Display(int x, float y ,string z).

    Here both method is same but sequence of data type parameter is change.

  • 8/12/2019 Method Overloading in C

    2/20

    EXAMPLE:-

    12

    3

    4

    5

    6

    7

    8

    9

    1011

    12

    13

    14

    15

    16

    17

    18

    1920

    21

    22

    23

    24

    25

    26

    27

    28

    usingSystem;

    namespacemethodoverloading{

    classProgram{

    staticvoidMain(string[] args){

    cls obj = newcls();

    obj.display(); //call first display method which takes noobj.display("neha"); //call second display method which takes one

    Console.ReadLine();}

    publicclasscls{

    publicvoiddisplay(){

    Console.WriteLine("HELLO");}

    publicvoiddisplay(stringsname){

    Console.WriteLine("HELLO"+ sname);

    }}

    }}

  • 8/12/2019 Method Overloading in C

    3/20

    Abstract Class and Abstract Method in C#

    Abstract Class:-we use 'abstract' keyword to implement the concept of abstract class.'Abstract

    class' can only inherited by other class.we can not create objects of 'abstract

    class'directly. When any 'abstract class'is inherited by other class then we create

    the objects of that derived class.We can not create objects of 'abstractclass' because methods of 'abstract class' only declare but not define.

    If any class will inherited the 'abstract class' then that derived class will give the

    body of the 'abstract class'member.

    Some characteristics of an 'abstract class' are:-

    It can not be instantiate directly.

    It can have abstract members.

    we can not apply a sealedmodifierto it.

    Example:-

    ?

    1

    2

    3

    4

    5

    67

    8

    9

    10

    11

    12

    13

    14

    1516

    abstractclassBase{............................. ............................. }classDerived:Base

    {............................. ............................. }

    Main Method(){Base b1; // Error

    Derived d1; // Ok

    }

    http://www.msdotnet.co.in/2012/06/access-specifier-or-modifier-in-c.htmlhttp://www.msdotnet.co.in/2012/06/access-specifier-or-modifier-in-c.htmlhttp://www.msdotnet.co.in/2012/06/access-specifier-or-modifier-in-c.htmlhttp://www.msdotnet.co.in/2012/07/abstract-class-and-abstract-method-in-c.htmlhttp://www.msdotnet.co.in/2012/07/abstract-class-and-abstract-method-in-c.htmlhttp://www.msdotnet.co.in/2012/07/abstract-class-and-abstract-method-in-c.htmlhttp://www.msdotnet.co.in/2012/06/access-specifier-or-modifier-in-c.html
  • 8/12/2019 Method Overloading in C

    4/20

    Abstract Method:-when we know what will happen but do not know how it happen ,we just only declare the

    method but do not define the method. In that case abstract keyword declare with method.

    when an instance method declaration includes the modifier abstract,the method is said to be

    anabstractmethod.

    What Is an Exception?

    An exception is an anomaly in your program that occurs atruntime(while your program is

    executing), that you usually could not have accounted for whilst writing your software. They

    are indeed used for exceptional circumstances.

    In .NET, a hierarchy of classes are used to represent all the different exceptions that could

    be thrown. The base class of this hierarchy is theException class,so all exception classes

    ultimately derive from the Exception class.

    You can also define your own custom exception classes, of which too must ultimately derive

    from the Exception class.

    Exception Base Class

    As theException classis the base class of all exception classes in .NET, it obviouslydefines some common features for all exceptions. The key properties are listed below

    (remember that all exception classes will have these properties as they all derive from the

    Exception class):

    http://http/msdn.microsoft.com/en-us/library/system.exception.aspxhttp://http/msdn.microsoft.com/en-us/library/system.exception.aspxhttp://http/msdn.microsoft.com/en-us/library/system.exception.aspxhttp://msdn.microsoft.com/en-us/library/system.exception.aspxhttp://msdn.microsoft.com/en-us/library/system.exception.aspxhttp://msdn.microsoft.com/en-us/library/system.exception.aspxhttp://msdn.microsoft.com/en-us/library/system.exception.aspxhttp://http/msdn.microsoft.com/en-us/library/system.exception.aspx
  • 8/12/2019 Method Overloading in C

    5/20

  • 8/12/2019 Method Overloading in C

    6/20

    Exception classes in C#

    There are some exception classes which is used for handling the Exception.All the Exception

    classes is derived from the two main classes.

    1. System.SystemException --->Predefined System Exception.

    2. System.ApplicationException-->Application program Exception.

    These two classes are used for Exception handling in C#.some derived Exception classes are:- FormatException

    DivideByZeroException

    NullReferenceException

    ArgumentNullException

    NotFiniteNumberException

    ArrayTypeMismatchException

    ArgumentOutOfRangeException

    ContextMarshalException

    StackOverflowException etc.

    using System;

    class Program

    {

    static void Main()

    {

    try

    {

    int value = 1 / int.Parse("0");

    Console.WriteLine(value);

    }

    catch (Exceptionex)

    {

    Console.WriteLine(ex.Message);

    }

    }

    }

  • 8/12/2019 Method Overloading in C

    7/20

    Access Specifier or Modifier in C#Visibility Control:- When we want to implement inheritance, it is important to understand

    ,how to establish visibility levels for our classes and their members. There are four types of a

    accessibility modifiers which may be applied to classes and members to specify their level

    of visibility.

    1. Public

    2. private

    3. protected

    4. internal

    Class Visibility:-

    Each class needs to specify its level of visibility. class visibility is used to decide which parts of

    the system can create class objects.In c# class can have one of the two visibility

    modifier publicor internal. If we do not explicitly mark the visibility modifier of a class, it

    is implicit set to 'internal' that is by default all classes are internal.

    Class marked public are accessible everywhere ,Both within and outside the program

    assembly.

    Class Member Visibility:- One of the goal of object oriented programming is data hiding. That

    is a class may be designed to hide its members from outside accessibility. C# provides a set

    of 'access modifiers'It specify the scope of type and its member up to which level they can be

    access.

  • 8/12/2019 Method Overloading in C

    8/20

    There are five access specifier in C#.

    1. Private:-Private member can be access only within the block { },where they have

    been declared. By default the class member are private.

    2. Protected:-protected member can be access within containing classes and

    Derived classes.

    OR

    Protected member is visible only to its own class and its derived classes.

    3. Internal:-Internal member can be access within Containing classes and Containing

    program.

    4.Protected Internal:-Protected Internal member is access within containing classes,

    Derived classes.and containing program.

    OR

    It is available in the containing program or assembly and in the Derived classes.

    5. Public:-Public member is access within containing classes,Derived classes, containing

    program, anywhere outside the containing program.

    OR

    Public member is accessible from anywhere outside the the class as well. It is also accessible

    in Derived classes.

    When no modifier is specified, it default to 'private'accessibility. It is important to remember

    that the accessibility of a member is never larger than that of the class containing it.

    You can easily understand all modifiers with the help of Diagram which is given below.

    See it:- Visibility of class member:

  • 8/12/2019 Method Overloading in C

    9/20

    http://2.bp.blogspot.com/-ce-JD3ChrvY/T9t9HO_n55I/AAAAAAAAAXk/mqMxM5ZPWtg/s1600/acc.PNG
  • 8/12/2019 Method Overloading in C

    10/20

    Class DescriptionImportant

    Properties\Methods

    DataSet

    Represents a locally cached subset of the total data

    stored in a data source or sources and provides a

    relational programming model for working with that data.

    Includes representations of tables, constraints, and

    relations between tables. A DataSetobject can be filled

    with data from multiple data sources.

    Properties include:

    TablesA collection

    ofDataTableobjects.

    RelationsA collection

    ofDataRelationobjects.

    DataTable

    Represents a table of data within a DataSet.ADataTablecan be created programmatically or as the

    result of a database query. Typically, an application

    accesses the data in a DataSetby iterating through

    theRowscollection of the appropriate DataTable.

    Properties include:

    RowsA collection

    of DataRowobjects.

    ColumnsA collection

    ofDataColumnobjects.

    DataRow/

    DataColumn

    Represent the rows and columns within DataTableobject.

    Use the column name to

    access a piece of data using

    syntax like the

    following:datum =

    MyDataRow["ColumnName

    DataRelation

    Represents a relation between a pair of DataTableobjects

    within a DataSet. Possible relations include one-to-many

    and parent-child.

    Add a DataRelationobject to

    aDataSetRelationscollection

    using the

    collection's Addmethod.

  • 8/12/2019 Method Overloading in C

    11/20

    Stored Procedure Advantages

    Transactions

    Although a stored procedure contains SQL commands, once compiled it will interact with SQL Server very

    differently from the way individual SQL statements (such as those passed from an ADO.NET command

    object) do. One of the key changes is that the SQL commands in a stored procedure are

    within transaction scope,which means that either all of the SQL statements in a stored procedure will

    execute, or none will. This is known as atomicity.

    Speed

    Unlike standard SQL statements, stored procedures are compiled and optimized by the database server.

    This optimization involves using information about the structure of a particular database that's required at

    execution time by the stored procedure. This process of storing execution information (theexecution

    plan)is a tremendous time saver, especially if the stored procedure is called many times.

    Speed is also improved by the fact that stored procedures run entirely on the database server - there's no

    need to pass large chunks of SQL code over a network. For a simple SELECT statement, that might not

    make a big difference, but in cases where we perform a series of loops and calculations, it can have a

    significant effect.

    Process Control

    A stored procedure can take advantage of control flow statements such as IF...ELSE,

    and FOR andWHILE loops, that are not typically available within a basic SELECT statement. This

    enables us to handle some quite complex logical operations from within SQL code. Without stored

    procedures, we'd need to create an object in the data layer to handle looping, producing a large amount

    of network traffic because of the number of records that would need to be processed.

    The use of control flow statements is key to any programming language, and by implementing this

    functionality in Transact-SQL, SQL Server bridges the gap between our code and the database.

    Security

    Stored procedures can also act as an additional security layer. For example, we could allow access to a

    stored procedure that generates an average salary for a company, while never allowing its users to see

    the salary information directly. If we implement security on our tables to prevent direct access, and then

    add a layer of stored procedures that users canaccess, we can enforce relationships and business logic

    that might otherwise be bypassed. A stored procedure acts a bit like a business object in component

    development: we don't let people call the data layer directly, instead forcing them to go through the

    business layer.

    Providing a secure database environment in a web application is especially important, since the webserver provides a convenient interface for hackers and others that would like to access areas that they

    have no business being in! The Web exposes our data to the outside world, so there is no such thing as a

    system that is too secure, or has been checked too many times. Implementing a layer of stored

    procedures that controls updates, insertions, and deletions can be of significant help.

    Reduced Network Traffic

    Using stored procedures enables a client application to pass control to a stored procedure on the

    database server. This allows the stored procedure to perform intermediate processing on the database

    server, without transmitting unnecessary data across the network.

  • 8/12/2019 Method Overloading in C

    12/20

    A properly designed application that processes large amounts of data using stored procedures returns

    only the data that is needed by the client. This reduces the amount of data transmitted across the

    network.

    Modularization

    The modularization of code is a key aspect of using stored procedures. Modularization is not only the

    process of writing reusable code units; it is also the process of maximizing team talents. If there's a strong

    database developer on a team, then we can let them write fast and efficient database code - in storedprocedures - while the component developers work on the business logic.

    Stored procedures enable easier maintenance. They are centralized, so we can reuse existing stored

    procedures throughout a system, and from external components. They are easier to access, to maintain,

    and to supervise.

    An SQL STATEMENT can be executed from within code in a .Net application or this SQL

    STATEMENT can be packaged into a database and kept / stored there hence becoming

    a stored procedure.

    Use of stored procedures increase the performance of a .net data driven application . Every

    time an SQL STATEMENT IS executed from a .net application , the statement is

    parsed,optimized and compiled by SQL SERVER whereas a stored procedure is parsed ,

    compiled and optimised only one time . Its also better to use stored procedures as its more

    secure coding practice

  • 8/12/2019 Method Overloading in C

    13/20

    The Command Class

    Each data provider has their Commandclass which is use to execute SQL commands or stored procedures to

    the database. Each Command class inherits from the System.Data.Common.DbCommandbase class. The

    following are the different flavors of the Command class for each data provider.

    Data Provider Command Class

    Sql Server SqlCommand

    OLE DB OleDbCommand

    ODBC OdbcCommand

    Figure 1 - Command Classes

    DbCommandimplements the IDbCommandinterface which exposes some properties and methods as shown in

    the following tables.

    Property Description

    CommandText Specifies the SQL command or stored procedure or a name of a table.

    CommandTimeoutSpecifies the time required to wait for the completion of a command before it throws an

    exception. The default is 30 seconds.

    CommandType

    Accepts a value from the System.Data.CommandTypeenumeration that will determine the

    type of command specified in the CommandTextproperty. It has 3 values, Text, for

    accepting SQL commands, StoredProcedurefor stored procedures, and TableDirectto

    get all the rows and columns of one or multiple tables. Note that by default, Textwill be

    used.

    Connection

    Specifies the connection that the command is associated to. The Commandclass must be

    hooked to an open connection which is the connection where the command is to be

    executed.

    Parameters A collection of Parameterdefined in the CommandText.

    FIgure 2 - IDbCommand Properties

    Property Description

    Cancel Tries to cancel the command being executed.

    CreateParameter Creates a new Parameterobject that can be added to Command.Parameterscollection.

    ExecuteReaderExecutes the command and returns a forward-only read-only cursor in the form of

    aDataReader.

    ExecuteNonQueryExecutes the command and returns the number of rows that were affected. Often used

    with record UPDATE, DELETE, or INSERT statements.

    ExecuteScalarExecutes the command, and retrieves a single value. Used with aggregate functions

    and in cases where you want to return the first column of the first row of a result set.

  • 8/12/2019 Method Overloading in C

    14/20

    Figure 3 - IDbCommand Methods

    We wll use the SQL Server provider's SqlCommandclass for the following examples. To create

    a Commandobject, you can simply use it's parameterless constructor.

    SqlCommand command = new SqlCommand();

    A command is useless without specifying the CommandTextwhich contains an SQL statement that the

    command will execute.

    command.CommandText = "SELECT * FROM Students";

    Alternatively, you can immediately specify the command text when creating the Commandobject using an

    overloaded constructor of SqlCommand.

    SqlCommand command = new SqlCommand("SELECT * FROM Students");

    Another required thing that the Commandobject should have is the Connectionobject where the command

    will be executed to. When you have created a Connection(for example, an SqlConnectionobject), then you

    can assign its instance to the Connectionproperty of the IDbCommand.

    SqlConnection connection = new SqlConnection();SqlCommand command = new SqlCommand();

    command.Connection = connection;

    An overloaded version of the constructor allows you to specify the command text and the connection to be

    used by the command.

    SqlCommand command = new SqlCommand("SELECT * FROM Students", connection);

    TheDbConnectionclass also offers a CreateCommand()method which returns a DbCommand with the

    connection already hooked to it. You can then use the CommandTextproperty to specify the command.

    SqlCommand command = connection.CreateCommand();command.CommandText = "SELECT * FROM Students";

    To execute commands, you first need an open connection. For reading the contents of a database, you

    can use the ExecuteReader()method which reaturns a DataReader object that can be used to step through

    each row of a database table. For updating, inserting, deleting, and any non-query commands, you can

    use the ExecuteNonQuery()method. These methods will be seen in action in a later lesson.

    Other properties and methods of the Commandclasses are reserved for later lessons. But for now, the ones

    introduced here are enough to execute basic SQL statements.

  • 8/12/2019 Method Overloading in C

    15/20

    The DataReader Class

    DataReaderobject allows forward-only, read-only access to a database. Using DataReaderis the connected

    way of accessing data and an open connection must be available first. Each provider has its own version

    ofDataReaderwhich inherits to the System.Data.Common.DbDataReaderbase class.

    Provider DataReader class

    SQL Server SqlDataReader

    OLE DB OleDbDataReader

    ODBC OdbcDataReader

    Figure 1 - DataReader Classes

    The DbDataReaderclass contains properties and methods used for reading a row in a database table. Some

    of this are presented in the following tables.

    Property Description

    FieldCount Specifies the number of columns of the current row or record.

    HasRows Specifies whether the current row has at least 1 row.

    IsClosed Specifies whether the DbDataReaderis closed.

    RecordsAffected Specifies the number of rows that has been updated, inserted, or deleted.

    Figure 2 - DbDataReader Properties

    Method Description

    GetBoolean Gets the value of a column as a boolean value.

    GetChar Gets the value of a column as a charvalue.

    GetDataTypeName Gets the name of the data type of the current column.

    GetDateTime Gets the value of the column as a DateTimeobject.

    GetDecimal Gets the value of the column as a decimalvalue.

    GetDouble Gets the value of the column as a doublevalue.

    GetFieldType Gets the field type of the specified column.

    GetInt32 Gets the value of the column as a intvalue.

    GetName Gets the name of the column.

    GetOrdinal Gets the column ordinal with the specified column name.

    GetString Gets the value of the column as a stringvalue.

    GetValue Gets the value of a column as an object.

    GetValues Gets all the column of a row as an array of objects.

    NextResultAdvances the reader to the next result when reading the

    results of a batch of statements.

  • 8/12/2019 Method Overloading in C

    16/20

    Method Description

    Read Advances the reader to the next record.

    Figure 3 - DbDataReader Methods

    The DataReaderonly loads a single row in the memory at a time to ensure the minimum use of

    memory.DataReadercan only be used when a connection is open, so you need to open a conenction first

    and as soon as you are over using it, then you must close the connection. A corresponding commandassigned with an SQL SELECT statement should call the ExecuteReader()method to create an instance

    of DbDataReaderobject. Again, we will use SQL Server provider for the following examples. (Suppose that a

    connection was already declared).

    SqlCommand command = new SqlCommand("SELECT * FROM Students", connection);SqlDataReader reader;

    connection.Open();reader = command.ExecuteReader();

    You can see that we first need an Openconnection before using the ExecuteReader()method. We did this

    using the DbConnection.Open() method. An overloaded version of the ExecuteReader() method also existsthat accepts a value from the System.Data.CommandBehaviorenumeration. Here are some of its values you

    can use.

    Value Description

    CloseConnection Immediately closes the connection when the Closemethod of the DataReaderis called.

    Default The default behavior of the DataReader.

    SingleResult The query returns a single result set.

    SingleRow The query is expected to return only a single row.

    Figure 4 - System.Data.CommandBehavior Enumeration Values

    For example, if you want the reader to only read a single row, then you should past the SingleRowvalue to

    the ExecutReader()method.

    reader = command.ExecuteReader(CommandBehavior.SingleRow);

    You can also combine command behaviors using the bitwise OR operator.

    reader = command.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.CloseConnection);

    Once the ExecuteReader()was executed and an instance of DbDataReaderwas placed in a variable, we cannow iterate through each record of the result set that was returned by by SELECT statement. The

    following shows you how to obtain the value of each field of every row.

    while (reader.Read()){

    MessageBox.Show(reader["FirstName"].ToString());}

    We used a for loop and inside its condition, we used the Read()method of the DataReaderto read the first

    row of the result set that was returned by the query. If a row was successfully read, the method will

    return true and continue the loop. Once that method is executed, we can used an indexer for

  • 8/12/2019 Method Overloading in C

    17/20

    the DataReaderobject and pass the name of the column. This will return the result as an object so we

    need to convert it first to its proper data type. After the body of the loop is executed, the Read()method is

    executed once again to read the next row. If there the row previously read is the last row and no other

    rows left to be read, then theRead()method will return false and stop the loop. Alternatively, you can use

    the Get methods of theDataReaderwhich accepts the column index of the value to be retrieved. For

    example, suppose we want to retrieve the StudentId which is a number, then you can use the following

    code.int studentID = reader.GetInt32(0);

    This will return the value of the first column (index 0) as a value of type int.

    After using the DataReader, you need to close the DataReaderand the Connectionto release the resources

    that was used and to make the connection availabe.

    reader.Close();connection.Close();

    We will use the DataReader classes to read the contents of a database in a connected fashion and it will

    be demonstrated in a later lesson.

  • 8/12/2019 Method Overloading in C

    18/20

    The Connection Class

    Each data provider in ADO.NET contains a Connectionclass that inherits from

    theSystem.Data.Common.DbConnectionclass. The DbConnectionserves as the base class for all

    the Connectionclasses of different data providers. The following are the Connectionclasses for each data

    provider.

    Data Provider Connection Class

    SQL Server SqlConnection

    OLE DB OleDbConnection

    ODBC OdbcConnection

    Figure 1 - Connection Classes

    The DbConnectionclass implements the IDbConnectioninterface which contains methods and properties

    that is used to define a connection and to open a connection to a data source. Openning a connection

    consumes resources of the computer so you need to close it as soon as possible. For you to open a

    connection, you must specify aConnection Stringto indicate the location, type and other configurations

    for connecting to a database source.

    The following are the methods and properties of the IDbConnectioninterface that are common to

    allConnectionclasses.

    Property Description

    ConnectionString Specifies the connection string to be used by the connection.

    ConnectionTimeoutSpecifies the time to wait for the connection to be established before declaring that

    the connection has timed out.

    Database Specifies the database that the connection is currently working on.

    State Specifies the current state of the connection.

    Figure 2 - IDbConnection Properties

    Method Description

    BeginTransaction Begins a database transaction.

    ChangeDatabase Changes the database the connection is currenly working on.

    Close Closes the connection.

    CreateCommand Creates and returns a command object associated with the connection.

    Open Opens the connection.

    Figure 3 - IDbConnection Methods

    Note that each Connection class of every data provider can have more properties and methods listed

    below which are unique to them. Let's use the SQL Server as the data provider for the following examples.

    It means that we will be using the SqlConnectionclass which is the Connection class of SQL Server data

    provider. To create a Connectionobject, simply use its parameterless constructor.

    http://visualcsharptutorials.com/2010/12/connection-strings/http://visualcsharptutorials.com/2010/12/connection-strings/http://visualcsharptutorials.com/2010/12/connection-strings/http://visualcsharptutorials.com/2010/12/connection-strings/
  • 8/12/2019 Method Overloading in C

    19/20

    SqlConnection connection = new SqlConnection();

    We need to specify the proper connection string for the connection. To assign a connection string to

    theConnectionobject, you can use the ConnectionStringproperty.

    connection.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=University;" +"Integrated Security=SSPI";

    Alternatively, you can use the overloaded constructor of the SqlConnectionclass when creating an

    instance of it.SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;" +

    "Initial Catalog=University;Integrated Security=SSPI");

    The connection string above specifies a connection to an SQL Server database using the University as the

    initial database with Window Authentication. The ConnectionStringproperty is set only when the

    connection is closed. The Connection class offers a number of properties that access the different

    components of the connection string.

    The Databaseproperty specifies the database to use. The initial database is indicated by the Initial Catalog

    parameter of the ConnectionString. To change the database to use, you can call

    the ChangeDatabasemethod as shown in the following code.connection.ChangeDatabase("AnotherDatabase");

    The code changes our database from University(specified in the connection string) to AnotherDatabase,

    provided that the AnotherDatabasedatabase exists.

    The ConnectionTimeoutproperty gets the value of the Connection Timeout parameter of the connection

    string. If it is not specified, it has a default value of 15. The Connection Timeout specifies how long the

    connection has to wait before it throws an exception indicating that a connection has timed out.

    To open a connection, we use the Openmethod. Be sure you have set the details needed in the connection

    string before calling this method. After you have used the database, you can use the Closemethod. Note

    that you can use the usingkeyword to automatically close the connection. This is shown below.using (SqlConnection connection = new SqlConnection()){

    // some code....connection.Open();// some code....

    }

    We put the declaration and initialization between the parentheses of the usingstatement. This means the

    the object created between these parentheses is only usable inside the block of the usingstatement. Once

    the closing blocked is reach, the Connectionobject is disposed automatically closing the connection. If you

    are using the Close method, be sure to always put it in the finally block like this.

    try{

    connection.Open();}catch(SqlException){}finally{

    connection.Close();}

  • 8/12/2019 Method Overloading in C

    20/20

    This is because, if you put it inside the try block, and an exception was thrown, then the statement that

    calls the Closemethod might not be reached leaving the connection open. If it is in the finally block, then

    theClosemethod will always be called. You can use the Stateproperty to know the current state of a

    connection, whether it is close or open. The State property accepts a value from

    theSystem.Data.ConnectionStateEnumeration. The following are the values of

    the ConnectionStateenumeration.

    Value Description

    Broken States that the connection is broken.

    Closed States that the conneciton is closed.

    Connecting States that the connection is currently connecting to a data source.

    Executing States that the connection is executing a command.

    Fetching States that the connection is retrieving data.

    Open States that the connection is open.

    Figure 4 - System.Data.ConnectionState Enumeration Values

    The Connectionclass offers two events that you can use. The first one is the InfoMessageevent which is

    used to get specific information messages. The StateChangeevent is triggered when the connection state

    is changed.

    static void con_StateChange(object sender, System.Data.StateChangeEventArgs e){

    Console.WriteLine("State has been changed from {0} to {1}.",e.OriginalState.ToString(), e.CurrentState.ToString());

    }

    static void Main(){

    SqlConnection con = new SqlConnection();con.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=University;" +

    "Integrated Security=SSPI";con.StateChange += new System.Data.StateChangeEventHandler(con_StateChange);con.Open(); // Opens a connectioncon.Close(); // Closes a connection

    }State has been changed from Closed to Open.State has been changed from Open to Closed.

    When we called the Open()method, the connection's state was changed from Closeto Open, triggering the

    event handler that is attached to the StateChangeevent. The event handler prints a message that showsthe OriginalStateand CurrentState. When we called the Close()method, the connection state was

    changed from Opento Closedalso trigerring the StateChangeevent.