<?xml version="1.0" encoding="UTF-8" standalone="no"?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:gd="http://schemas.google.com/g/2005" xmlns:georss="http://www.georss.org/georss" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:thr="http://purl.org/syndication/thread/1.0"><id>tag:blogger.com,1999:blog-979102946207364014</id><updated>2026-03-23T00:16:23.929+05:30</updated><category term="C# Types"/><category term="C# Generics"/><category term="Constraints in C#"/><category term="Operators"/><category term="Variables"/><category term="C# Program Execution"/><category term="Enumeration in C#"/><category term="Logical Operators"/><category term="Type conversion"/><category term="c# sample program"/><category term="Animated Tray Icon in C#"/><category term="Application Domain"/><category term="Arithmetic Operators"/><category term="Bool Type"/><category term="C# Animation"/><category term="C# Collections"/><category term="C# Directory size calculation"/><category term="C# Double Buffering"/><category term="C# Dynamic Print Preview"/><category term="C# File Operations"/><category term="C# File Version Information"/><category term="C# File or Directory Attributes"/><category term="C# Find File Info"/><category term="C# Find Installed Printers"/><category term="C# Images in Thumbnail"/><category term="C# JIT"/><category term="C# Non-Rectangular Shapes in Form"/><category term="C# Object Oriented Programming"/><category term="C# Print Jobs Management"/><category term="C# Printing Multipages"/><category term="C# Printing Simple Document"/><category term="C# Printing Wrapped Text"/><category term="C# Scrollable Image"/><category term="C# Shapes"/><category term="C# Simple Beep Sound"/><category term="C# WAV or MP3 sounds"/><category term="Class Library"/><category term="Connecting to an ODBC Data Source in ADO"/><category term="Controling the Execution of a Thread"/><category term="Create a Thread-Safe Collection Instance"/><category term="Creating a Custom Attribute"/><category term="Data Tables in C#"/><category term="Database Access in C#"/><category term="Decimal Type"/><category term="Drag-Drop Operation in C#"/><category term="Encapsulation"/><category term="Encryption in c#"/><category term="Ensure That Only One Instance of an Application Can Execute Concurrently"/><category term="Execute a Method Asynchronously"/><category term="Execute a Method Using a New Thread"/><category term="Execute a Method Using a Timer"/><category term="Execute a Method Using the Thread Pool"/><category term="Execute a Method by Signaling a WaitHandle Object"/><category term="Execution in Command line"/><category term="Finding Installed Fonts in C#"/><category term="Floating Type"/><category term="Force a List Box to Scroll"/><category term="How To Know When a Thread Finishes"/><category term="IComparer in C#"/><category term="Identifiers"/><category term="Immovable Form"/><category term="Including code at Build Time"/><category term="Indentations"/><category term="Inheritance"/><category term="Inspecting Attributes Using Reflection"/><category term="Instantiate an Object Using Reflection"/><category term="Integers"/><category term="Keywords"/><category term="Lifetime of Variables"/><category term="Linking Context Menu"/><category term="Main Menu as Context Menu"/><category term="Movable Borderless Form"/><category term="Multilingual Form in C#"/><category term="OOP"/><category term="Output Options in C#"/><category term="Polymorphism"/><category term="Positioning"/><category term="Relational Operators"/><category term="Retrieve Type Information"/><category term="SQL in C#"/><category term="Scope of Variables"/><category term="Screen Capture in C#"/><category term="Semicolons"/><category term="Sort an Array List"/><category term="Sorting List View"/><category term="Start a New Process"/><category term="Strong Name in C#"/><category term="Synchronize the Execution of Multiple Threads"/><category term="Syntax Errors"/><category term="Terminate a Process"/><category term="Test an Object's Type"/><category term="Text  Box Restriction"/><category term="Type Casting"/><category term="Unloading Assemblies and App Domains"/><category term="Using AutoComplete combo box"/><category term="Using Visual Studio IDE"/><category term="Validate an Input Control C#"/><category term="Value Types"/><category term="Windows Registry to Save Size of Form"/><category term="XML - Append Nodes"/><category term="XML - Creating Schema"/><category term="XML - Find Element"/><category term="XML - Generating Class"/><category term="XML - Get Nodes"/><category term="XML - Read Write into Memory"/><category term="XML - Serialization"/><category term="XML - Validate XML Doc"/><category term="XML - XPath Search"/><category term="XML - XSL"/><category term="Xml - Insert Nodes"/><category term="code library"/><category term="code module"/><category term="command line arguments"/><category term="literals"/><category term="using VS IDE in C#"/><title type="text">C# Slackers</title><subtitle type="html">Chapter wise Information about C# topics from basics to Development level. Browse through Topics for more details.</subtitle><link href="http://csharp-slackers.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default?redirect=false" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/" rel="alternate" type="text/html"/><link href="http://pubsubhubbub.appspot.com/" rel="hub"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default?start-index=26&amp;max-results=25&amp;redirect=false" rel="next" type="application/atom+xml"/><author><name>satish</name><uri>http://www.blogger.com/profile/11104095808954112849</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><generator uri="http://www.blogger.com" version="7.00">Blogger</generator><openSearch:totalResults>167</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><xhtml:meta content="noindex" name="robots" xmlns:xhtml="http://www.w3.org/1999/xhtml"/><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-4116182353827766400</id><published>2008-11-02T23:39:00.001+05:30</published><updated>2008-11-02T23:39:48.195+05:30</updated><title type="text">Execute SQL Command or Stored Procedure</title><content type="html">&lt;p class="first-para"&gt;The &lt;em&gt;IDbCommand&lt;/em&gt; interface represents a database command, and each data provider includes a unique implementation. Here is the list of &lt;em&gt;IDbCommand&lt;/em&gt; implementations for the five standard data providers.&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.Odbc.OdbcCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OleDb.OleDbCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OracleClient.OracleCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlServerCe.SqlCeCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlClient.SqlCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;To execute a command against a database you must have an open connection and a properly configured command object appropriate to the type of database you are accessing. You can create command objects directly using a constructor, but a simpler approach is to use the &lt;em&gt;CreateCommand&lt;/em&gt; factory method of a connection object. The &lt;em&gt;CreateCommand&lt;/em&gt; method returns a command object of the correct type for the data provider and configures it with basic information obtained from the connection you used to create the command. Before executing the command, you must configure the properties described in Table, which are common to all command implementations.&lt;/p&gt;
&lt;table width="90%" border="1" class="table"&gt;
&lt;caption class="table-title"&gt;&lt;span class="table-title"&gt;&lt;span class="table-titlelabel"&gt;Table:&lt;/span&gt; Common Command Object Properties&lt;/span&gt;&lt;/caption&gt;
&lt;thead&gt;
&lt;tr valign="top"&gt;
&lt;th scope="col" align="left" class="th" width="23%"&gt;
&lt;p class="table-para"&gt;Property&lt;/p&gt;
&lt;/th&gt;
&lt;th scope="col" align="left" class="th" width="77%"&gt;
&lt;p class="table-para"&gt;Description&lt;/p&gt;
&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandText&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;string&lt;/em&gt; containing the text of the SQL command to execute or the name of a stored procedure. The content of the &lt;em&gt;CommandText&lt;/em&gt; property must be compatible with the value you specify in the &lt;em&gt;CommandType&lt;/em&gt; property.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandTimeout&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;An &lt;em&gt;int&lt;/em&gt; that specifies the number of seconds to wait for the command to return before timing out and raising an exception. Defaults to 30 seconds.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandType&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A value of the &lt;em&gt;System.Data.CommandType&lt;/em&gt; enumeration that specifies the type of command represented by the command object. For most data providers, valid values are &lt;em&gt;StoredProcedure&lt;/em&gt;, when you want to execute a stored procedure, and &lt;em&gt;Text&lt;/em&gt;, when you want to execute a SQL text command. If you are using the OLE DB Data Provider, you can specify &lt;em&gt;TableDirect&lt;/em&gt; when you want to return the entire contents of one or more tables; refer to the .NET Framework SDK documentation for more details. Defaults to &lt;em&gt;Text&lt;/em&gt;.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Connection&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;An &lt;em&gt;IDbConnection&lt;/em&gt; instance that provides the connection to the database on which you will execute the command. If you create the command using the &lt;em&gt;IDbConnection.CreateCommand&lt;/em&gt; method, this property will be automatically set to the &lt;em&gt;IDbConnection&lt;/em&gt; instance from which you created the command.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Parameters&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;System.Data.IDataParameterCollection&lt;/em&gt; instance containing the set of parameters to substitute into the command.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Transaction&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;System.Data.IDbTransaction&lt;/em&gt; instance representing the transaction into which to enlist the command. (See the .NET Framework SDK documentation for details about transactions.)&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p class="para"&gt;Once you have configured your command object, there are a number of ways to execute it depending on the nature of the command, the type of data returned by the command, and the format in which you want to process the data.&lt;/p&gt;
&lt;p class="para"&gt;To execute a command, such as &lt;strong&gt;INSERT&lt;/strong&gt;, &lt;strong&gt;DELETE&lt;/strong&gt;, or &lt;strong&gt;CREATE TABLE&lt;/strong&gt;, that doesn't return database data, call &lt;em&gt;ExecuteNonQuery&lt;/em&gt;. For the &lt;strong&gt;UPDATE&lt;/strong&gt;, &lt;strong&gt;INSERT&lt;/strong&gt;, and &lt;strong&gt;DELETE&lt;/strong&gt; commands, &lt;em&gt;ExecuteNonQuery&lt;/em&gt; method returns an &lt;em&gt;int&lt;/em&gt; that specifies the number of rows affected by the command. For other commands, such as &lt;strong&gt;CREATE TABLE&lt;/strong&gt;, &lt;em&gt;ExecuteNonQuery&lt;/em&gt; returns the value -1. Here is an example that uses &lt;strong&gt;UPDATE&lt;/strong&gt; to modify a record.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteNonQueryExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.Text;
    com.CommandText = "UPDATE Employees SET Title = 'Sales Director'" +
        " WHERE EmployeeId = '5'";

    // Execute the command and process the result.
    int result = com.ExecuteNonQuery();

    if (result == 1) {
        Console.WriteLine("Employee title updated.");
    } else {
        Console.WriteLine("Employee title not updated.");
    }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;To execute a command that returns a result set, such as a &lt;strong&gt;SELECT&lt;/strong&gt; statement or stored procedure, use the &lt;em&gt;ExecuteReader&lt;/em&gt; method. &lt;em&gt;ExecuteReader&lt;/em&gt; returns an &lt;em&gt;IDataReader&lt;/em&gt; instance through which you have access to the result data. Most data providers also allow you to execute multiple SQL commands in a single call to the &lt;em&gt;ExecuteReader&lt;/em&gt; method. This code excerpt uses the &lt;em&gt;ExecuteReader&lt;/em&gt; method to execute the Ten Most Expensive Products stored procedure from the Northwind database and display the results to the console.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteReaderExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.StoredProcedure;
    com.CommandText = "Ten Most Expensive Products";

    // Execute the command and process the results
    using (IDataReader reader = com.ExecuteReader()) {

        Console.WriteLine("Price of the Ten Most Expensive Products.");

        while (reader.Read()) {

            // Display the product details.
            Console.WriteLine("  {0} = {1}", 
                reader["TenMostExpensiveProducts"],
                reader["UnitPrice"]);
        }
    }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;If you want to execute a query but only need the value from the first column of the first row of result data, use the &lt;em&gt;ExecuteScalar&lt;/em&gt; method. The value is returned as an &lt;em&gt;object&lt;/em&gt; reference that you must cast to the correct type. Here is an example.&lt;/p&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteScalarExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.Text;
    com.CommandText = "SELECT COUNT(*) FROM Employees";

    // Execute the command and cast the result.
    int result = (int)com.ExecuteScalar();

    Console.WriteLine("Employee count = " + result);
}
&lt;/pre&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/4116182353827766400/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/execute-sql-command-or-stored-procedure.html#comment-form" rel="replies" title="21 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/4116182353827766400" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/4116182353827766400" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/execute-sql-command-or-stored-procedure.html" rel="alternate" title="Execute SQL Command or Stored Procedure" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>21</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-5374279009132183409</id><published>2008-11-02T23:36:00.001+05:30</published><updated>2008-11-02T23:36:54.603+05:30</updated><title type="text">Connection Pooling</title><content type="html">&lt;p class="first-para"&gt;Connection pooling significantly reduces the overhead associated with creating and destroying database connections. Connection pooling also improves the scalability of solutions by reducing the number of concurrent connections a database must maintain-many of which sit idle for a significant portion of their lifetimes. With connection pooling, instead of creating and opening a new connection object whenever you need one, you take an already open connection from the connection pool. When you have finished using the connection, instead of closing it, you return it to the pool and allow other code to use it.&lt;/p&gt;
&lt;p class="para"&gt;The SQL Server and Oracle data providers encapsulate connection- pooling functionality that they enable by default. One connection pool exists for each unique connection string you specify when you open a new connection. Each time you open a new connection with a connection string that you have used previously, the connection is taken from the existing pool. Only if you specify a different connection string will the data provider create a new connection pool. You can control some characteristics of your pool using the connection string settings described in below table.&lt;/p&gt;
&lt;table width="90%" border="1" class="table"&gt;
&lt;caption class="table-title"&gt;&lt;span class="table-title"&gt;&lt;span class="table-titlelabel"&gt;Table:&lt;/span&gt; Connection String Settings That Control Connection Pooling&lt;/span&gt;&lt;/caption&gt;
&lt;thead&gt;
&lt;tr valign="top"&gt;
&lt;th scope="col" align="left" class="th" width="20%"&gt;
&lt;p class="table-para"&gt;Setting&lt;/p&gt;
&lt;/th&gt;
&lt;th scope="col" align="left" class="th" width="80%"&gt;
&lt;p class="table-para"&gt;Description&lt;/p&gt;
&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Connection Lifetime&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the maximum time in seconds that a connection is allowed to live in the pool before it's closed. The age of a connection is tested only when the connection is returned to the pool. This setting is useful for minimizing pool size if the pool isn't heavily used and also ensures optimal load balancing is achieved in clustered database environments. The default value is 0, which means connections exist for the life of the current process.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Connection Reset&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Supported only by the SQL Server data provider. Specifies whether connections are reset as they are taken from the pool. A value of "True" ensures a connection's state is reset but requires an additional communication with the database. The default value is "True".&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Max Pool Size&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the maximum number of connections that should be in the pool. Connections are created and added to the pool as required until this figure is reached. If a request for a connection is made but there are no free connections, the caller will block until a connection becomes available. The default value is 100.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Min Pool Size&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the minimum number of connections that should be in the pool. On pool creation, this number of connections are created and added to the pool. During periodic maintenance, or when a connection is requested, connections are added to the pool to ensure the minimum number of connections is available. The default value is 0.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Pooling&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Set to "False" to obtain a non-pooled connection. The default value is "True".&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p class="para"&gt;This code excerpt from the sample code for this recipe demonstrates the configuration of a connection pool that contains a minimum of 5 and a maximum of 15 connections. Connections expire after 10 minutes (600 seconds) and are reset each time a connection is obtained from the pool.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Obtain a pooled connection.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;" +    // local SQL Server instance
        "Database = Northwind;" +       // the sample Northwind DB
        "Integrated Security = SSPI;" + // integrated Windows security
        "Min Pool Size = 5;" +          // configure minimum pool size
        "Max Pool Size = 15;" +         // configure maximum pool size
        "Connection Reset = True;" +    // reset connections each use
        "Connection Lifetime = 600";    // set maximum connection lifetime

    // Open the Database connection.
    con.Open();

    // Access the database...
    

    // At the end of the using block, the Dispose calls Close, which
    // returns the connection to the pool for reuse.
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;This code excerpt demonstrates how to use the &lt;em&gt;Pooling&lt;/em&gt; setting to obtain a connection object that isn't from a pool. This is useful if your application uses a single long-lived connection to a database.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Obtain a non-pooled connection.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;" +    // local SQL Server instance
        "Database = Northwind;" +       // the sample Northwind DB
        "Integrated Security = SSPI;" + // integrated Windows security
        "Pooling = False";              // specify non-pooled connection

    // Open the Database connection.
    con.Open();

    // Access the database...
    

    // At the end of the using block, the Dispose calls Close, which
    // closes the non-pooled connection.
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="last-para"&gt;The ODBC and OLE DB data providers also support connection pooling, but they don't implement connection pooling within managed .NET classes and you don't configure the pool in the same way as for the SQL Server or Oracle data providers. ODBC connection pooling is managed by the ODBC Driver Manager and configured using the ODBC Data Source Administrator tool in the Control Panel. OLE DB connection pooling is managed by the native OLE DB implementation; the most you can do is disable pooling by including the setting &lt;span class="fixed"&gt;"OLE DB Services=-4;"&lt;/span&gt; in your connection string. The SQL Server CE data provider doesn't support connection pooling because SQL Server CE supports only a single concurrent connection.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/5374279009132183409/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/connection-pooling.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5374279009132183409" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5374279009132183409" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/connection-pooling.html" rel="alternate" title="Connection Pooling" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-3219044537335536979</id><published>2008-11-02T23:33:00.001+05:30</published><updated>2008-11-02T23:33:26.809+05:30</updated><title type="text">Connecting to Database</title><content type="html">&lt;p class="first-para"&gt;The first step in database access is to open a connection to the database. The &lt;em&gt;IDbConnection&lt;/em&gt; interface represents a database connection, and each data provider includes a unique implementation. Here is the list of &lt;em&gt;IDbConnection&lt;/em&gt; implementations for the five standard data providers.&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.Odbc.OdbcConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OleDb.OleDbConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OracleClient.OracleConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlServerCe.SqlCeConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlClient.SqlConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;You configure a connection object using a connection string. A connection string is a set of semicolon-separated name value pairs. You can supply a connection string either as a constructor argument or by setting a connection object's &lt;em&gt;ConnectionString&lt;/em&gt; property before opening the connection. Each connection class implementation requires that you provide different information in the connection string. Refer to the &lt;em&gt;ConnectionString&lt;/em&gt; property documentation for each implementation to see the values you can specify. Possible settings include the following:&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;The name of the target database server&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;The name of the database to open initially&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Connection timeout values&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Connection-pooling behavior&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Authentication mechanisms to use when connecting to secured databases, including provision of user names and passwords&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;Once configured, call the connection object's &lt;em&gt;Open&lt;/em&gt; method to open the connection to the database. You can then use the connection object to execute commands against the data source. The properties of a connection object also allow you to retrieve information about the state of a connection and the settings used to open the connection. When you're finished with a connection, you should always call its &lt;em&gt;Close&lt;/em&gt; method to free up the underlying database connection and system resources. &lt;em&gt;IDbConnection&lt;/em&gt; extends &lt;em&gt;System.IDisposable&lt;/em&gt;, meaning that each connection class implements the &lt;em&gt;Dispose&lt;/em&gt; method. &lt;em&gt;Dispose&lt;/em&gt; automatically calls &lt;em&gt;Close&lt;/em&gt;, making the &lt;em&gt;using&lt;/em&gt; statement a very clean and efficient way of using connection objects in your code.&lt;/p&gt;
&lt;p class="para"&gt;You achieve optimum scalability by opening your database connection as late as possible and closing it again as soon as you have finished. This ensures that you don't tie up database connections for long periods and give all code the maximum opportunity to obtain a connection. This is especially important if you are using connection pooling.&lt;/p&gt;
&lt;p class="para"&gt;The code shown here demonstrates how to use the &lt;em&gt;SqlConnection&lt;/em&gt; class to open a connection to a SQL Server database running on the local machine that uses integrated Windows security. To access a remote machine, simply change the data source name from &lt;em&gt;localhost&lt;/em&gt; to the name of your database instance.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Create an empty SqlConnection object.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;"+ // local SQL Server instance
        "Database = Northwind;" +   // the sample Northwind DB
        "Integrated Security=SSPI"; // integrated Windows security

    // Open the Database connection.
    con.Open();

    // Display information about the connection.
    if (con.State == ConnectionState.Open) {
        Console.WriteLine("SqlConnection Information:");
        Console.WriteLine("  Connection State = " + con.State);
        Console.WriteLine("  Connection String = " + 
            con.ConnectionString);
        Console.WriteLine("  Database Source = " + con.DataSource);
        Console.WriteLine("  Database = " + con.Database);
        Console.WriteLine("  Server Version = " + con.ServerVersion);
        Console.WriteLine("  Workstation Id = " + con.WorkstationId);
        Console.WriteLine("  Timeout = " + con.ConnectionTimeout);
        Console.WriteLine("  Packet Size = " + con.PacketSize);
    } else {
        Console.WriteLine("SqlConnection failed to open.");
        Console.WriteLine("  Connection State = " + con.State);
    }
    // At the end of the using block Dispose() calls Close().
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;As another example, the following program shows the connection string used to open a connection to the same database if you were using the OLE DB data provider to provide connectivity.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Create an empty OleDbConnection object.
using (OleDbConnection con = new OleDbConnection()) {

    // Configure the OleDbConnection object's connection string.
    con.ConnectionString = 
        "Provider = SQLOLEDB;" +         // OLE DB Provider for SQL Server
        "Data Source = localhost;" +     // local SQL Server instance
        "Initial Catalog = Northwind;" + // the sample Northwind DB
        "Integrated Security=SSPI";      // integrated Windows security

    // Open the Database connection.
    con.Open();

}
&lt;/pre&gt;&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/3219044537335536979/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/connecting-to-database.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/3219044537335536979" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/3219044537335536979" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/11/connecting-to-database.html" rel="alternate" title="Connecting to Database" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-7194648585806488513</id><published>2008-10-30T11:40:00.000+05:30</published><updated>2008-10-30T11:43:09.325+05:30</updated><title type="text">Generic Interfaces</title><content type="html">&lt;div class="first-para"&gt;The data type upon which it operates is now  specified by a type parameter.&lt;/div&gt;&lt;div class="informalexample"&gt; &lt;div class="widecontent"&gt;&lt;pre class="programlisting"&gt;// Demonstrate a generic interface.

using System;

public interface ISeries&lt;t&gt; {
  T getNext(); // return next element in series
  void reset(); // restart the series
  void setStart(T v); // set the starting element
}

// Implement ISeries.
class ByTwos&lt;t&gt; : ISeries&lt;t&gt; {
  T start;
  T val;

  // This delegate defines the form of a method
  // that will be called when the next element in
  // the series is needed.
  public delegate T IncByTwo(T v);

  // This delegate reference will be assigned the
  // method passed to the ByTwos constructor.
  IncByTwo incr;&lt;a href="" name="926"&gt;&lt;/a&gt;&lt;a href="" name="IDX-520"&gt;&lt;/a&gt;
  public ByTwos(IncByTwo incrMeth) {
    start = default(T);
    val = default(T);
    incr = incrMeth;
  }

  public T getNext() {
    val = incr(val);
    return val;
  }

  public void reset() {
    val = start;
  }

  public void setStart(T v) {
    start = v;
    val = start;
  }
}

class ThreeD {
  public int x, y, z;

  public ThreeD(int a, int b, int c) {
    x = a;
    y = b;
    z = c;
  }
}

class GenIntfDemo {
  // Define plus two for int.
  static int intPlusTwo(int v) {
    return v + 2;
  }

  // Define plus two for double.
  static double doublePlusTwo(double v) {
    return v + 2.0;
  }

  // Define plus two for ThreeD.
  static ThreeD ThreeDPlusTwo(ThreeD v) {
    if(v==null) return new ThreeD(0, 0, 0);
    else return new ThreeD(v.x + 2, v.y + 2, v.z + 2);
  }

  public static void Main() {
    // Demonstrate int series.
    ByTwos&lt;int&gt; intBT = new ByTwos&lt;int&gt;(intPlusTwo);

    for(int i=0; i &amp;lt; 5; i++)
      Console.Write(intBT.getNext() + "  ");&lt;a href="" name="927"&gt;&lt;/a&gt;&lt;a href="" name="IDX-521"&gt;&lt;/a&gt;
    Console.WriteLine();


    // Demonstrate double series.
    ByTwos&lt;double&gt; dblBT = new ByTwos&lt;double&gt;(doublePlusTwo);

    dblBT.setStart(11.4);

    for(int i=0; i &amp;lt; 5; i++)
      Console.Write(dblBT.getNext() + "  ");

    Console.WriteLine();


    // Demonstrate ThreeD series.
    ByTwos&lt;threed&gt; ThrDBT = new ByTwos&lt;threed&gt;(ThreeDPlusTwo);

    ThreeD coord;
    for(int i=0; i &amp;lt; 5; i++) {
      coord = ThrDBT.getNext();
      Console.Write(coord.x + "," +
                    coord.y + "," +
                    coord.z + "  ");
    }

    Console.WriteLine();

  }
}&lt;/threed&gt;&lt;/threed&gt;&lt;/double&gt;&lt;/double&gt;&lt;/int&gt;&lt;/int&gt;&lt;/t&gt;&lt;/t&gt;&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="para"&gt;The output is shown here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;2  4  6  8  10
13.4  15.4  17.4  19.4  21.4
0,0,0  2,2,2  4,4,4  6,6,6  8,8,8&lt;/pre&gt;&lt;pre class="programlisting"&gt;&amp;nbsp;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;There are several things of interest in the preceding example.  First, notice how &lt;b class="bold"&gt;ISeries&lt;/b&gt; is declared:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;public interface ISeries&lt;t&gt; {&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;As mentioned, a generic interface uses a syntax similar to that of  a generic class.&lt;/div&gt;&lt;div class="para"&gt;Now, notice how &lt;b class="bold"&gt;ByTwos&lt;/b&gt;, which implements &lt;b class="bold"&gt;ISeries&lt;/b&gt;, is declared:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class ByTwos&lt;t&gt; : ISeries&lt;t&gt; {&lt;/t&gt;&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;The type parameter &lt;b class="bold"&gt;T&lt;/b&gt; is specified by &lt;b class="bold"&gt;ByTwos&lt;/b&gt; and is also specified in &lt;b class="bold"&gt;ISeries&lt;/b&gt;. This  is important. A class that implements a generic interface must, itself, be  generic. For example, the following declaration would be illegal:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class ByTwos : ISeries&lt;t&gt; { // Wrong!&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;The type argument required by a generic interface must be passed  to the implementing class. Otherwise, there is no way for the interface to  receive the type argument. &lt;a href="" name="928"&gt;&lt;/a&gt;&lt;a href="" name="IDX-522"&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="para"&gt;Next, the current value of the series, &lt;b class="bold"&gt;val&lt;/b&gt;, and  the starting value, &lt;b class="bold"&gt;start&lt;/b&gt;, are declared to be objects of the  generic type &lt;b class="bold"&gt;T&lt;/b&gt;. Then, a delegate called &lt;b class="bold"&gt;IncByTwo&lt;/b&gt; is declared. This delegate defines the form of a method  that will be used to increase an object of type &lt;b class="bold"&gt;T&lt;/b&gt; by two. In  order for &lt;b class="bold"&gt;ByTwos&lt;/b&gt; to work with any type of data, there must be  some way to define what an increase by two means for each type of data. This is  achieved by passing to the &lt;b class="bold"&gt;ByTwos&lt;/b&gt; constructor a reference to a  method that performs an increase by two. This reference is stored in &lt;b class="bold"&gt;incr&lt;/b&gt;. When the next element in the series is needed, that method  is called through the &lt;b class="bold"&gt;incr&lt;/b&gt; delegate to obtain the next value  in the series.&lt;/div&gt;&lt;div class="para"&gt;Notice the class &lt;b class="bold"&gt;ThreeD&lt;/b&gt;. It encapsulates  three-dimensional (X, Y, Z) coordinates. It is used to demonstrate &lt;b class="bold"&gt;ByTwos&lt;/b&gt; on a class type.&lt;/div&gt;&lt;div class="para"&gt;In &lt;b class="bold"&gt;GenIntfDemo&lt;/b&gt;, three increment methods are  declared: one for &lt;b class="bold"&gt;int&lt;/b&gt;, one for &lt;b class="bold"&gt;double&lt;/b&gt;, and  one for objects of type &lt;b class="bold"&gt;ThreeD&lt;/b&gt;. These are passed to the &lt;b class="bold"&gt;ByTwos&lt;/b&gt; constructor when objects of their respective types are  created. Pay special attention to &lt;b class="bold"&gt;ThreeDPlusTwo( )&lt;/b&gt;, shown  here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;// Define plus two for ThreeD.
static ThreeD ThreeDPlusTwo(ThreeD v) {
  if(v==null) return new ThreeD(0, 0, 0);
  else return new ThreeD(v.x + 2, v.y + 2, v.z + 2);
}&lt;/pre&gt;&lt;pre class="programlisting"&gt;&amp;nbsp;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Notice that it first checks if &lt;b class="bold"&gt;v&lt;/b&gt; is &lt;b class="bold"&gt;null&lt;/b&gt;. If it is, then it returns a new &lt;b class="bold"&gt;ThreeD&lt;/b&gt;  object in which all fields are set to zero. The reason for this is that &lt;b class="bold"&gt;v&lt;/b&gt; is set to &lt;b class="bold"&gt;default(T)&lt;/b&gt; by the &lt;b class="bold"&gt;ByTwos&lt;/b&gt; constructor. This value is zero for value types and &lt;b class="bold"&gt;null&lt;/b&gt; for object types. Thus, (unless &lt;b class="bold"&gt;setStart(  )&lt;/b&gt; has been called) for the first increment, &lt;b class="bold"&gt;v&lt;/b&gt; will contain  &lt;b class="bold"&gt;null&lt;/b&gt; instead of a reference to an object. This means that for  the first increment, a new object is required.&lt;/div&gt;&lt;div class="para"&gt;A type parameter for a generic interface can have constraints in  the same way that it can for a generic class. For example, this version of &lt;b class="bold"&gt;ISeries&lt;/b&gt; restricts its use to reference types:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;public interface ISeries&lt;t&gt; where T : class {&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;When this version of &lt;b class="bold"&gt;ISeries&lt;/b&gt; is implemented, the  implementing class must also specify the same constraint for &lt;b class="bold"&gt;T&lt;/b&gt;, as shown here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class ByTwos&lt;t&gt; : ISeries&lt;t&gt; where T : class {&lt;/t&gt;&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="last-para"&gt;Because of the reference constraint, this version of &lt;b class="bold"&gt;ISeries&lt;/b&gt; cannot be used on value types. Thus, in the preceding  program, only &lt;b class="bold"&gt;ByTwos&lt;threed&gt;&lt;/threed&gt;&lt;/b&gt; would be valid. &lt;b class="bold"&gt;ByTwos&lt;int&gt;&lt;/int&gt;&lt;/b&gt; and &lt;b class="bold"&gt;ByTwos&lt;double&gt;&lt;/double&gt;&lt;/b&gt;  would be invalid.&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/7194648585806488513/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-interfaces.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7194648585806488513" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7194648585806488513" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-interfaces.html" rel="alternate" title="Generic Interfaces" type="text/html"/><author><name>satish</name><uri>http://www.blogger.com/profile/11104095808954112849</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-5353243297058888220</id><published>2008-10-30T11:34:00.000+05:30</published><updated>2008-10-30T11:37:58.543+05:30</updated><title type="text">Generic Delegates</title><content type="html">&lt;div class="para"&gt;Like methods, delegates can also be generic. The syntax is similar  to that of a generic method, with the type parameter being specified after the  delegate’s name. To declare a generic delegate, use this general form:&lt;/div&gt;&lt;pre class="literallayout-normal"&gt;delegate &lt;i class="emphasis"&gt;ret-type delegate-name&lt;/i&gt;&amp;lt;&lt;i class="emphasis"&gt;type-parameter-list&lt;/i&gt;&amp;gt;(&lt;i class="emphasis"&gt;arg-list&lt;/i&gt;);&lt;/pre&gt;&lt;div class="para"&gt;Notice the placement of the type parameter list. It immediately  follows the delegate’s name. The advantage of generic delegates is that they let  you define, in a type-safe manner, a generalized form that can then be matched  to any specific type of method.&lt;/div&gt;&lt;div class="para"&gt;The following program demonstrates a generic delegate called &lt;b class="bold"&gt;SomeOp&lt;/b&gt; that has one type parameter called &lt;b class="bold"&gt;T&lt;/b&gt;. It  returns type &lt;b class="bold"&gt;T&lt;/b&gt; and takes an argument of type &lt;b class="bold"&gt;T&lt;/b&gt;.&lt;/div&gt;&lt;div class="informalexample"&gt; &lt;div class="widecontent"&gt;&lt;pre class="programlisting"&gt;// A simple generic delegate.

using System;

// Declare a generic delegate.
delegate T SomeOp&lt;t&gt;(T v);

class GenDelegateDemo {
  // Return the summation of the argument.
  static int sum(int v) {
    int result = 0;
    for(int i=v; i&amp;gt;0; i--)
      result += i;

    return result;
  }

  // Return a string containing the reverse of the argument.
  static string reflect(string str) {
    string result = "";

    foreach(char ch in str)
      result = ch + result;

    return result;
  }

  public static void Main() {
    // Construct an int delegate. Notice use of method group
    // conversion on generic delegate.
    SomeOp&lt;int&gt; intDel = sum;
    Console.WriteLine(intDel(3));

    // Construct a string delegate. Also use method group conversion.
    SomeOp&lt;string&gt; strDel = reflect;
    Console.WriteLine(strDel("Hello"));
  }
}&lt;/string&gt;&lt;/int&gt;&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;a href="" name="922"&gt;&lt;/a&gt;&lt;a href="" name="IDX-517"&gt;&lt;/a&gt; &lt;div class="para"&gt;The output is shown here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;6
olleH&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Let’s look closely at this program. First, notice how the &lt;b class="bold"&gt;SomeOp&lt;/b&gt; delegate is declared:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;delegate T SomeOp&lt;t&gt;(T v);&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Notice that &lt;b class="bold"&gt;T&lt;/b&gt; can be used as the return type  even though the type parameter &lt;b class="bold"&gt;T&lt;/b&gt; is specified after the name  &lt;b class="bold"&gt;SomeOp&lt;/b&gt;.&lt;/div&gt;&lt;div class="para"&gt;Inside &lt;b class="bold"&gt;GenDelegateDemo&lt;/b&gt;, the methods &lt;b class="bold"&gt;sum( )&lt;/b&gt; and &lt;b class="bold"&gt;reflect( )&lt;/b&gt; are declared, as shown  here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;static int sum(int v) {

static string reflect(string str) {&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;The &lt;b class="bold"&gt;sum( )&lt;/b&gt; method returns the summation of the  integer value passed as an argument. The &lt;b class="bold"&gt;reflect( )&lt;/b&gt; method  returns a string that is the reverse of the string passed as an argument.&lt;/div&gt;&lt;div class="para"&gt;Inside &lt;b class="bold"&gt;Main( )&lt;/b&gt;, a delegate called &lt;b class="bold"&gt;intDel&lt;/b&gt; is instantiated and assigned a reference to &lt;b class="bold"&gt;sum( )&lt;/b&gt;:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;SomeOp&lt;int&gt; intDel = sum;&lt;/int&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Because &lt;b class="bold"&gt;sum( )&lt;/b&gt; takes an &lt;b class="bold"&gt;int&lt;/b&gt;  argument and returns an &lt;b class="bold"&gt;int&lt;/b&gt; value, &lt;b class="bold"&gt;sum( )&lt;/b&gt; is  compatible with an &lt;b class="bold"&gt;int&lt;/b&gt; instance of &lt;b class="bold"&gt;SomeOp&lt;/b&gt;.  Notice that the new C# 2.0 method group conversion syntax is used to assign &lt;b class="bold"&gt;sum&lt;/b&gt; to &lt;b class="bold"&gt;intDel&lt;/b&gt;. Method group conversions are  fully compatible with generic delegates.&lt;/div&gt;&lt;div class="para"&gt;In similar fashion, the delegate &lt;b class="bold"&gt;strDel&lt;/b&gt; is  created and assigned a reference to &lt;b class="bold"&gt;reflect( )&lt;/b&gt;:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;SomeOp&lt;string&gt; strDel = reflect;&lt;/string&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Because &lt;b class="bold"&gt;reflect( )&lt;/b&gt; takes a string argument and  returns a &lt;b class="bold"&gt;string&lt;/b&gt; result, it is compatible with the string  version of &lt;b class="bold"&gt;SomeOp&lt;/b&gt;.&lt;/div&gt;&lt;div class="para"&gt;Because of the type-safety inherent in generics, you cannot assign  incompatible methods to delegates. For example, assuming the preceding program,  the following statement would be in error:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;SomeOp&lt;int&gt; intDel = reflect; // Error!&lt;/int&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;Because &lt;b class="bold"&gt;reflect( )&lt;/b&gt; takes a string argument and  returns a string result, it cannot be assigned to an &lt;b class="bold"&gt;int&lt;/b&gt;  version of &lt;b class="bold"&gt;SomeOp&lt;/b&gt;.&lt;/div&gt;&lt;div class="para"&gt;&lt;/div&gt;&lt;div class="informalexample"&gt; &lt;div class="widecontent"&gt;&lt;pre class="programlisting"&gt;// Convert event example from Chapter 15 to
// use generic delegate.

using System;&lt;a href="" name="923"&gt;&lt;/a&gt;&lt;a href="" name="IDX-518"&gt;&lt;/a&gt;
// Derive a class from EventArgs.
class MyEventArgs : EventArgs {
  public int eventnum;
}

// Declare a generic delegate for an event.
delegate void MyEventHandler&lt;t, v=""&gt;(T source, V args);

// Declare an event class.
class MyEvent {
  static int count = 0;

  public event MyEventHandler&lt;myevent, myeventargs=""&gt; SomeEvent;

  // This fires SomeEvent.
  public void OnSomeEvent() {
    MyEventArgs arg = new MyEventArgs();

    if(SomeEvent != null) {
      arg.eventnum = count++;
      SomeEvent(this, arg);
    }
  }
}

class X {
  public void handler&lt;t, v=""&gt;(T source, V arg) where V : MyEventArgs {
    Console.WriteLine("Event " + arg.eventnum +
                      " received by an X object.");
    Console.WriteLine("Source is " + source);
    Console.WriteLine();
  }
}

class Y {
  public void handler&lt;t,v&gt;(T source, V arg) where V : MyEventArgs {
    Console.WriteLine("Event " + arg.eventnum +
                      " received by a Y object.");
    Console.WriteLine("Source is " + source);
    Console.WriteLine();
  }
}

class UseGenericEventDelegate {
  public static void Main() {
    X ob1 = new X();
    Y ob2 = new Y();
    MyEvent evt = new MyEvent();

    // Add handler() to the event list.
    evt.SomeEvent += ob1.handler;
    evt.SomeEvent += ob2.handler;&lt;a href="" name="924"&gt;&lt;/a&gt;&lt;a href="" name="IDX-519"&gt;&lt;/a&gt;
    // Fire the event.
    evt.OnSomeEvent();
    evt.OnSomeEvent();
  }
}&lt;/t,v&gt;&lt;/t,&gt;&lt;/myevent,&gt;&lt;/t,&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;&lt;div class="para"&gt;The output is shown here:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;Event 0 received by an X object.
Source is MyEvent

Event 0 received by a Y object.
Source is MyEvent

Event 1 received by an X object.
Source is MyEvent

Event 1 received by a Y object.
Source is MyEvent&lt;/pre&gt;&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/5353243297058888220/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-delegates.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5353243297058888220" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5353243297058888220" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-delegates.html" rel="alternate" title="Generic Delegates" type="text/html"/><author><name>satish</name><uri>http://www.blogger.com/profile/11104095808954112849</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-4853071458142654420</id><published>2008-10-30T11:24:00.000+05:30</published><updated>2008-10-30T11:34:31.965+05:30</updated><title type="text">Using Multiple Constraints</title><content type="html">&lt;div class="first-para"&gt;There can be more than one constraint associated with a  parameter. When this is the case, use a comma-separated list of constraints. In  this list, the first constraint must be &lt;b class="bold"&gt;class&lt;/b&gt; or &lt;b class="bold"&gt;struct&lt;/b&gt; (if present), or the base class (if one is specified). It  is illegal to specify both a &lt;b class="bold"&gt;class&lt;/b&gt; or &lt;b class="bold"&gt;struct&lt;/b&gt;  constraint and a base class constraint. Next, must come any interface  constraints. The &lt;b class="bold"&gt;new( )&lt;/b&gt; constraint must be last. For example,  this is a valid declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class Gen&lt;t&gt; where T : MyClass, IMyInterface, new() { // ...&lt;/t&gt;&lt;/pre&gt;&lt;/div&gt;&lt;a href="" name="908"&gt;&lt;/a&gt;&lt;a href="" name="IDX-509"&gt;&lt;/a&gt; &lt;div class="para"&gt;In this case, &lt;b class="bold"&gt;T&lt;/b&gt; must be replaced by a type  argument that inherits &lt;b class="bold"&gt;MyClass&lt;/b&gt;, implements &lt;b class="bold"&gt;IMyInterface&lt;/b&gt;, and has a parameterless constructor.&lt;/div&gt;&lt;div class="para"&gt;When using two or more type parameters, you can specify a  constraint for each parameter by using a separate &lt;b class="bold"&gt;where&lt;/b&gt;  clause. For example:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;// Use multiple where clauses.

using System;

// Gen has two type arguments and both have
// a where clause.
class Gen&lt;t, v=""&gt; where T : class
                where V : struct {
  T ob1;
  V ob2;

  public Gen(T t, V v) {
    ob1 = t;
    ob2 = v;
  }
}

class MultipleConstraintDemo {
  public static void Main() {
    // This is OK because string is a class and
    // int is a value type.
    Gen&lt;string, int=""&gt; obj = new Gen&lt;string, int=""&gt;("test", 11);

    // The next line is wrong because bool is not
    // a reference type.
//    Gen&lt;bool, int=""&gt; obj = new Gen&lt;bool, int=""&gt;(true, 11);

  }
}&lt;/bool,&gt;&lt;/bool,&gt;&lt;/string,&gt;&lt;/string,&gt;&lt;/t,&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;In this example, &lt;b class="bold"&gt;Gen&lt;/b&gt; takes two type arguments,  and both have a &lt;b class="bold"&gt;where&lt;/b&gt; clause. Pay special attention to its  declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class Gen&lt;t, v=""&gt; where T : class
                where V : struct {&lt;/t,&gt;&lt;/pre&gt;&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/4853071458142654420/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-multiple-constraints.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/4853071458142654420" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/4853071458142654420" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-multiple-constraints.html" rel="alternate" title="Using Multiple Constraints" type="text/html"/><author><name>satish</name><uri>http://www.blogger.com/profile/11104095808954112849</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-1381474606831516607</id><published>2008-10-27T19:35:00.002+05:30</published><updated>2008-10-30T11:33:29.770+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Constraints in C#"/><title type="text">Using Constraint to Establish Relationship Between Two Type Parameters</title><content type="html">&lt;div class="first-para"&gt;One of the more interesting aspects of the base class constraint is that it allows you to establish a relationship between two type parameters. For example, consider the following generic class declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class Gen&amp;lt;T, V&amp;gt; where V : T {
&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;In this declaration, the &lt;b&gt;where&lt;/b&gt; clause tells the compiler that &lt;b&gt;V&lt;/b&gt; must inherit &lt;b&gt;T&lt;/b&gt;. If this relationship is not present when an object of type &lt;b&gt;Gen&lt;/b&gt; is declared, then a compile-time error will result. A constraint that uses a type parameter, such as that just shown, is called a &lt;i&gt;naked type constraint.&lt;/i&gt; The following example illustrates this constraint:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;// Create relationship between two type parameters.

using System;

class A {
  //...
}

class B : A {
  // ...
}

// Here, V must inherit T.
class Gen&amp;lt;T, V&amp;gt; where V : T {
  // ...
}

class NakedConstraintDemo {
  public static void Main() {

    // This declaration is OK because B inherits A.
    Gen&amp;lt;A, B&amp;gt; x = new Gen&amp;lt;A, B&amp;gt;();

    // This declaration is in error because
    // A does not inherit B.
//    Gen&amp;lt;B, A&amp;gt; y = new Gen&amp;lt;B, A&amp;gt;();

  }
}
&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;First, notice that class &lt;b&gt;B&lt;/b&gt; inherits class &lt;b&gt;A&lt;/b&gt;. Next, examine the two &lt;b&gt;Gen&lt;/b&gt; declarations in &lt;b&gt;Main( )&lt;/b&gt;. As the comments explain, the first declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;Gen&amp;lt;A, B&amp;gt; x = new Gen&amp;lt;A, B&amp;gt;();
&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;is legal because &lt;b&gt;B&lt;/b&gt; inherits &lt;b&gt;A&lt;/b&gt;. However, the second declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;//    Gen&amp;lt;B, A&amp;gt; y = new Gen&amp;lt;B, A&amp;gt;();
&lt;/pre&gt;&lt;/div&gt;&lt;div class="last-para"&gt;is illegal because &lt;b&gt;A&lt;/b&gt; does not inherit &lt;b&gt;B&lt;/b&gt;.&lt;/div&gt;&lt;div class="section"&gt;&lt;h3 class="sect3-title"&gt;Using Multiple Constraints&lt;/h3&gt;&lt;div class="first-para"&gt;There can be more than one constraint associated with a parameter. When this is the case, use a comma-separated list of constraints. In this list, the first constraint must be &lt;b&gt;class&lt;/b&gt; or &lt;b&gt;struct&lt;/b&gt; (if present), or the base class (if one is specified). It is illegal to specify both a &lt;b&gt;class&lt;/b&gt; or &lt;b&gt;struct&lt;/b&gt; constraint and a base class constraint. Next, must come any interface constraints. The &lt;b&gt;new( )&lt;/b&gt; constraint must be last. For example, this is a valid declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class Gen&amp;lt;T&amp;gt; where T : MyClass, IMyInterface, new() { // ...
&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;In this case, &lt;b&gt;T&lt;/b&gt; must be replaced by a type argument that inherits &lt;b&gt;MyClass&lt;/b&gt;, implements &lt;b&gt;IMyInterface&lt;/b&gt;, and has a parameterless constructor.&lt;/div&gt;&lt;div class="para"&gt;When using two or more type parameters, you can specify a constraint for each parameter by using a separate &lt;b&gt;where&lt;/b&gt; clause. For example:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;// Use multiple where clauses.

using System;

// Gen has two type arguments and both have
// a where clause.
class Gen&amp;lt;T, V&amp;gt; where T : class
                where V : struct {
  T ob1;
  V ob2;

  public Gen(T t, V v) {
    ob1 = t;
    ob2 = v;
  }
}

class MultipleConstraintDemo {
  public static void Main() {
    // This is OK because string is a class and
    // int is a value type.
    Gen&amp;lt;string, int&amp;gt; obj = new Gen&amp;lt;string, int&amp;gt;("test", 11);

    // The next line is wrong because bool is not
    // a reference type.
//    Gen&amp;lt;bool, int&amp;gt; obj = new Gen&amp;lt;bool, int&amp;gt;(true, 11);

  }
}
&lt;/pre&gt;&lt;/div&gt;&lt;div class="para"&gt;In this example, &lt;b&gt;Gen&lt;/b&gt; takes two type arguments, and both have a &lt;b&gt;where&lt;/b&gt; clause. Pay special attention to its declaration:&lt;/div&gt;&lt;div class="informalexample"&gt;&lt;pre class="programlisting"&gt;class Gen&amp;lt;T, V&amp;gt; where T : class
                where V : struct {
&lt;/pre&gt;&lt;/div&gt;&lt;div class="last-para"&gt;Notice that the only thing that separates the first &lt;b&gt;where&lt;/b&gt; clause from the second is whitespace. No other punctuation is required or valid.&lt;/div&gt;&lt;/div&gt;&lt;div class="zoundry_raven_tags" xmlns=""&gt;Technorati : &lt;a class="ztag" href="http://www.technorati.com/tag/Constraints+in+C%23" rel="tag"&gt;Constraints in C#&lt;/a&gt;  &lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/1381474606831516607/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-constraint-to-establish.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1381474606831516607" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1381474606831516607" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-constraint-to-establish.html" rel="alternate" title="Using Constraint to Establish Relationship Between Two Type Parameters" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-1630916516174455291</id><published>2008-10-27T19:33:00.001+05:30</published><updated>2008-10-27T19:33:23.827+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Constraints in C#"/><title type="text">Reference Type and Value Type Constraints</title><content type="html">&lt;p class="first-para"&gt;The last two constraints which explained in the previous posts enable you to indicate that a type argument must be either a reference type or a value type. These constraints are useful in the few cases where the difference between reference and value types is important to generic code. The general forms of the &lt;strong&gt;where&lt;/strong&gt; statements for these constraints are shown here:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
where &lt;em&gt;T&lt;/em&gt; : class

where &lt;em&gt;T&lt;/em&gt; : struct
&lt;/pre&gt;
&lt;p class="para"&gt;Here, &lt;em&gt;T&lt;/em&gt; is the name of the type parameter. When additional constraints are present, &lt;strong&gt;class&lt;/strong&gt; or &lt;strong&gt;struct&lt;/strong&gt; must be the first constraint in the list.&lt;/p&gt;
&lt;p class="para"&gt;Here is an example that demonstrates the reference type constraint:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Demonstrate a reference constraint.

using System;
class MyClass {
  //...
}

// Use a reference constraint.
class Test&amp;lt;T&amp;gt; where T : class {
  T obj;

  public Test() {
    // The following statement is legal only
    // because T is guaranteed to be a reference
    // type, which can be assigned the value null.
    obj = null;
  }

  // ...
}

class ClassConstraintDemo {
  public static void Main() {

    // The following is OK because MyClass is a class.
    Test&amp;lt;MyClass&amp;gt; x = new Test&amp;lt;MyClass&amp;gt;();

    // The next line is in error because int is
    // a value type.
//    Test&amp;lt;int&amp;gt; y = new Test&amp;lt;int&amp;gt;();
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;First, notice how &lt;strong&gt;Test&lt;/strong&gt; is declared:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class Test&amp;lt;T&amp;gt; where T : class {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;The &lt;strong&gt;class&lt;/strong&gt; constraint requires that any type argument for &lt;strong&gt;T&lt;/strong&gt; be a reference type. In this program, this is necessary because of what occurs inside the &lt;strong&gt;Test&lt;/strong&gt; constructor:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
public Test() {
  // The following statement is legal only
  // because T is guaranteed to be a reference
  // type, which can be assigned the value null.
  obj = null;
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Here, &lt;strong&gt;obj&lt;/strong&gt; (which is of type &lt;strong&gt;T&lt;/strong&gt;) is assigned the value &lt;strong&gt;null&lt;/strong&gt;. This assignment is valid only for reference types. In C#, you cannot assign &lt;strong&gt;null&lt;/strong&gt; to a value type. Therefore, without the constraint, the assignment would not have been valid, and the compile would have failed. This is one case in which the difference between value types and reference types might be important to a generic routine.&lt;/p&gt;
&lt;p class="para"&gt;The value type constraint is the complement of the reference type constraint. It simply ensures that any type argument is a value type, including a &lt;strong&gt;struct&lt;/strong&gt; or an &lt;strong&gt;enum&lt;/strong&gt;. Here is an example: &lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Demonstrate a value type constraint.

using System;

struct MyStruct {
  //...
}

class MyClass {
  // ...
}

class Test&amp;lt;T&amp;gt; where T : struct {
  T obj;

  public Test(T x) {
    obj = x;
  }

  // ...
}

class ValueConstraintDemo {
  public static void Main() {

    // Both of these declarations are legal.

    Test&amp;lt;MyStruct&amp;gt; x = new Test&amp;lt;MyStruct&amp;gt;(new MyStruct());

    Test&amp;lt;int&amp;gt; y = new Test&amp;lt;int&amp;gt;(10);

    // But, the following declaration is illegal!
//    Test&amp;lt;MyClass&amp;gt; z = new Test&amp;lt;MyClass&amp;gt;(new MyClass());
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;In this program, &lt;strong&gt;Test&lt;/strong&gt; is declared as shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class Test&amp;lt;T&amp;gt; where T : struct {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="last-para"&gt;Because &lt;strong&gt;T&lt;/strong&gt; of &lt;strong&gt;Test&lt;/strong&gt; now has the &lt;strong&gt;struct&lt;/strong&gt; constraint, &lt;strong&gt;T&lt;/strong&gt; can be passed only value type arguments. This means that &lt;strong&gt;Test&amp;lt;MyStruct&amp;gt;&lt;/strong&gt; and &lt;strong&gt;Test&amp;lt;int&amp;gt;&lt;/strong&gt; are valid, but &lt;strong&gt;Test&amp;lt;MyClass&amp;gt;&lt;/strong&gt; is not. To prove this, try removing the comment symbol from the start of the last line in the program and recompiling. An error will be reported.&lt;/p&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/Constraints+in+C%23" class="ztag" rel="tag"&gt;Constraints in C#&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/1630916516174455291/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/reference-type-and-value-type.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1630916516174455291" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1630916516174455291" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/reference-type-and-value-type.html" rel="alternate" title="Reference Type and Value Type Constraints" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-268291228584773773</id><published>2008-10-27T19:31:00.001+05:30</published><updated>2008-10-27T19:31:14.563+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Constraints in C#"/><title type="text">Using Interface Constraint</title><content type="html">&lt;p class="first-para"&gt;The interface constraint enables you to specify an interface that a type argument must implement. The interface constraint serves the same two important purposes as the base class constraint. First, it lets you use the members of the interface within the generic class. Second, it ensures that only type arguments that implement the specified interface are used. This means that for any given interface constraint, the type argument must be either the interface or a class that implements that interface.&lt;/p&gt;
&lt;p class="para"&gt;The interface constraint uses this form of the &lt;strong&gt;where&lt;/strong&gt; clause:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
where &lt;em&gt;T&lt;/em&gt; : &lt;em&gt;interface-name&lt;/em&gt;
&lt;/pre&gt;
&lt;p class="para"&gt;Here, &lt;em&gt;T&lt;/em&gt; is the name of the type parameter, and &lt;em&gt;interface-name&lt;/em&gt; is the name of the interface. More than one interface can be specified by using a comma-separated list. If a constraint includes both a base class and interface, then the base class must be listed first.&lt;/p&gt;
&lt;p class="para"&gt;The following program illustrates the interface constraint by reworking the telephone list example shown in the previous section. In this version, the &lt;strong&gt;PhoneNumber&lt;/strong&gt; class has been converted into an interface called &lt;strong&gt;IPhoneNumber&lt;/strong&gt;. This interface is then implemented by &lt;strong&gt;Friend&lt;/strong&gt; and &lt;strong&gt;Supplier&lt;/strong&gt;.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Use an interface constraint.

using System;

// A custom exception that is thrown if a name or number
// is not found.
class NotFoundException : ApplicationException { }

// An interface that supports a name and phone number.
public interface IPhoneNumber {

  string Number {
    get;
    set;
  }

  string Name {
    get;
    set;
  }
}

// A class of phone numbers for friends.
// It implements IPhoneNumber.
class Friend : IPhoneNumber {
  string name;
  string number;

  bool isWorkNumber;

  public Friend(string n, string num, bool wk) {
    name = n;
    number = num;

    isWorkNumber = wk;
  }

  public bool IsWorkNumber {
    get {
      return isWorkNumber;
    }
  }

  // Implement IPhoneNumber
  public string Number {
    get { return number; }
    set { number = value; }
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }

  // ...
}

// A class of phone numbers for suppliers.
class Supplier : IPhoneNumber {
  string name;
  string number;

  public Supplier(string n, string num) {
    name = n;
    number = num;
  }
  // Implement IPhoneNumber
  public string Number {
    get { return number; }
    set { number = value; }
  }

  public string Name {
    get { return name; }
    set { name = value; }
  }

  // ...
}

// Notice that this class does not implement IPhoneNumber.
class EmailFriend {

  // ...
}

// PhoneList can manage any type of phone list
// as long as it implements IPhoneNumber.
class PhoneList&amp;lt;T&amp;gt; where T : IPhoneNumber {
  T[] phList;
  int end;

  public PhoneList() {
    phList = new T[10];
    end = 0;
  }

  public bool add(T newEntry) {
    if(end == 10) return false;

    phList[end] = newEntry;
    end++;

    return true;
  }

  // Given a name, find and return the phone info.
  public T findByName(string name) {

    for(int i=0; i&amp;lt;end; i++) {

      // Name can be used because it is a member of
      // IPhoneNumber, which is the interface constraint.
      if(phList[i].Name == name)
        return phList[i];

    }

    // Name not in list.
    throw new NotFoundException();
  }
  // Given a number, find and return the phone info.
  public T findByNumber(string number) {

    for(int i=0; i&amp;lt;end; i++) {

      // Number can be used because it is also a member of
      // IPhoneNumber, which is the interface constraint.
      if(phList[i].Number == number)
        return phList[i];
    }

    // Number not in list.
    throw new NotFoundException();
  }

  // ...
}

// Demonstrate interface constraints.
class UseInterfaceConstraint {
  public static void Main() {

    // The following code is OK because Friend
    // implements IPhoneNumber.
    PhoneList&amp;lt;Friend&amp;gt; plist = new PhoneList&amp;lt;Friend&amp;gt;();
    plist.add(new Friend("Tom", "555-1234", true));
    plist.add(new Friend("Gary", "555-6756", true));
    plist.add(new Friend("Matt", "555-9254", false));

    try {
      // Find the number of a friend given a name.
      Friend frnd = plist.findByName("Gary");

      Console.Write(frnd.Name + ": " + frnd.Number);

      if(frnd.IsWorkNumber)
        Console.WriteLine(" (work)");
      else
        Console.WriteLine();
    } catch(NotFoundException) {
      Console.WriteLine("Not Found");
    }

    Console.WriteLine();

    // The following code is also OK because Supplier
    // implements IPhoneNumber.
    PhoneList&amp;lt;Supplier&amp;gt; plist2 = new PhoneList&amp;lt;Supplier&amp;gt;();
    plist2.add(new Supplier("Global Hardware", "555-8834"));
    plist2.add(new Supplier("Computer Warehouse", "555-9256"));
    plist2.add(new Supplier("NetworkCity", "555-2564"));

    try {
      // Find the name of a supplier given a number
      Supplier sp = plist2.findByNumber("555-2564");
      Console.WriteLine(sp.Name + ": " + sp.Number);
    } catch(NotFoundException) {
        Console.WriteLine("Not Found");
    }

    // The following declaration is invalid
    // because EmailFriend does NOT implement IPhoneNumber.
//    PhoneList&amp;lt;EmailFriend&amp;gt; plist3 =
//        new PhoneList&amp;lt;EmailFriend&amp;gt;(); // Error!
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section"&gt;
&lt;h3 class="sect3-title"&gt;Using the new( ) Constructor Constraint&lt;/h3&gt;
&lt;p class="first-para"&gt;The &lt;strong&gt;new( )&lt;/strong&gt; constructor constraint enables you to instantiate an object of a generic type. Normally, you cannot create an instance of a generic type parameter. However, the &lt;strong&gt;new( )&lt;/strong&gt; constraint changes this because it requires that a type argument supply a parameterless constructor. (This parameterless constructor can be the default constructor provided automatically when no explicit constructor is declared.) With the &lt;strong&gt;new( )&lt;/strong&gt; constraint in place, you can invoke the parameterless constructor to create an object.&lt;/p&gt;
&lt;p class="para"&gt;Here is a simple example that illustrates the use of &lt;strong&gt;new( )&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Demonstrate a new() constructor constraint.

using System;

class MyClass {

  public MyClass() {
    // ...
  }

  //...
}

class Test&amp;lt;T&amp;gt; where T : new() {
  T obj;

  public Test() {
    // This works because of the new() constraint.
    obj = new T(); // create a T object
  }

  // ...
}

class ConsConstraintDemo {
  public static void Main() {

    Test&amp;lt;MyClass&amp;gt; x = new Test&amp;lt;MyClass&amp;gt;();

  }
}
&lt;/pre&gt;&lt;/div&gt;

&lt;p class="para"&gt;First, notice the declaration of the &lt;strong&gt;Test&lt;/strong&gt; class, shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class Test&amp;lt;T&amp;gt; where T : new() {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Because of the &lt;strong&gt;new( )&lt;/strong&gt; constraint, any type argument must supply a parameterless constructor. As explained, this can be the default constructor or one that you create.&lt;/p&gt;
&lt;p class="para"&gt;Next, examine the &lt;strong&gt;Test&lt;/strong&gt; constructor, shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
public Test() {
  // This works because of the new() constraint.
  obj = new T(); // create a T object
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;A new object of type &lt;strong&gt;T&lt;/strong&gt; is created, and a reference to it is assigned to &lt;strong&gt;obj&lt;/strong&gt;. This statement is valid only because the &lt;strong&gt;new( )&lt;/strong&gt; constraint ensures that a constructor will be available. To prove this, try removing the &lt;strong&gt;new( )&lt;/strong&gt; constraint, and then attempt to recompile the program. As you will see, an error will be reported.&lt;/p&gt;
&lt;p class="para"&gt;In &lt;strong&gt;Main( )&lt;/strong&gt;, an object of type &lt;strong&gt;Test&lt;/strong&gt; is instantiated, as shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Test&amp;lt;MyClass&amp;gt; x = new Test&amp;lt;MyClass&amp;gt;();
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Notice that the type argument is &lt;strong&gt;MyClass&lt;/strong&gt; and that &lt;strong&gt;MyClass&lt;/strong&gt; defines a parameterless constructor. Thus, it is valid for use as a type argument for &lt;strong&gt;Test&lt;/strong&gt;. It must be pointed out that it was not necessary for &lt;strong&gt;MyClass&lt;/strong&gt; to explicitly declare a parameterless constructor. Its default constructor would also satisfy the constraint. However, if a class needs other constructors in addition to a parameterless one, then it would be necessary to also explicitly declare a parameterless version.&lt;/p&gt;
&lt;p class="last-para"&gt;Two important points about using &lt;strong&gt;new( )&lt;/strong&gt;: First, it can be used with other constraints, but it must be the last constraint in the list. Second, &lt;strong&gt;new( )&lt;/strong&gt; allows you to construct an object using only the parameterless constructor, even when other constructors are available. In other words, it is not permissible to pass arguments to the constructor of a type parameter.&lt;/p&gt;
&lt;/div&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/Constraints+in+C%23" class="ztag" rel="tag"&gt;Constraints in C#&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/268291228584773773/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-interface-constraint.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/268291228584773773" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/268291228584773773" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-interface-constraint.html" rel="alternate" title="Using Interface Constraint" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-6722170351608747010</id><published>2008-10-27T19:25:00.001+05:30</published><updated>2008-10-27T19:26:00.056+05:30</updated><title type="text">Constrained Types in Generics</title><content type="html">&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class Gen&amp;lt;T&amp;gt; {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;any type can be passed to &lt;strong&gt;T&lt;/strong&gt;. Thus, it is legal to create &lt;strong&gt;Gen&lt;/strong&gt; objects in which &lt;strong&gt;T&lt;/strong&gt; is replaced by &lt;strong&gt;int&lt;/strong&gt;, &lt;strong&gt;double&lt;/strong&gt;, &lt;strong&gt;string&lt;/strong&gt;, &lt;strong&gt;FileStream&lt;/strong&gt;, or any other type. Although having no restrictions on the type argument is fine for many purposes, sometimes it is useful to limit the types that can be passed to a type parameter. For example, you might want to create a method that operates on the contents of a stream, including a &lt;strong&gt;FileStream&lt;/strong&gt; or &lt;strong&gt;MemoryStream&lt;/strong&gt;. This situation seems perfect for generics, but you need some way to ensure that only stream types are used as type arguments. You don't want to allow a type argument of &lt;strong&gt;int&lt;/strong&gt;, for example. You also need some way to tell the compiler that the methods defined by a stream will be available for use. For example, your generic code needs some way to know that it can call the &lt;strong&gt;Read( )&lt;/strong&gt; method.&lt;/p&gt;
&lt;p class="para"&gt;To handle such situations, C# provides &lt;em&gt;constrained types.&lt;/em&gt; When specifying a type parameter, you can specify a constraint that the type parameter must satisfy. This is accomplished through the use of a &lt;strong&gt;where&lt;/strong&gt; clause when specifying the type parameter, as shown here:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
class &lt;em&gt;class-name&lt;/em&gt;&amp;lt;&lt;em&gt;type-param&lt;/em&gt;&amp;gt; where &lt;em&gt;type-param&lt;/em&gt; : &lt;em&gt;constraints&lt;/em&gt; { // ...
&lt;/pre&gt;
&lt;p/&gt;
&lt;p class="para"&gt;Here, &lt;em&gt;constraints&lt;/em&gt; is a comma-separated list of constraints.&lt;/p&gt;
&lt;p class="para"&gt;There are five types of constraints:&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;You can require that a certain base class be present in a type argument by using a &lt;em&gt;base class constraint.&lt;/em&gt; This constraint is specifi ed by naming the desired base class.&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;You can require that one or more interfaces be implemented by a type argument by using an &lt;em&gt;interface constraint.&lt;/em&gt; This constraint is specified by naming the desired interface.&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;You can require that the type argument supply a parameterless constructor. This is called a &lt;em&gt;constructor constraint.&lt;/em&gt; It is specified by &lt;strong&gt;new( )&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;You can specify that a type argument must be a reference type by specifying the &lt;em&gt;reference type constraint&lt;/em&gt;: &lt;strong&gt;class&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;You can specify that the type argument be a value type by specifying the &lt;em&gt;value type&lt;/em&gt; &lt;em&gt;constraint&lt;/em&gt;: &lt;strong&gt;struct&lt;/strong&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;Of these constraints, the base class constraint and the interface constraint are probably the most often used, with the remaining adding fine-grained control. Each of the constraints is examined in detailed in next posts.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/6722170351608747010/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/constrained-types-in-generics.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6722170351608747010" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6722170351608747010" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/constrained-types-in-generics.html" rel="alternate" title="Constrained Types in Generics" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-6929499622421123489</id><published>2008-10-25T01:19:00.000+05:30</published><updated>2008-10-25T01:20:00.474+05:30</updated><title type="text">Using Explicit Type Arguments to Call Generic Method</title><content type="html">&lt;p class="first-para"&gt;Although implicit type inference is adequate for most invocations of a generic method, it is possible to explicitly specify the type argument. To do so, specify the type argument after the method name when calling the method. For example, here &lt;strong&gt;copyInsert( )&lt;/strong&gt; is explicitly passed type &lt;strong&gt;string&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
ArrayUtils.copyInsert&amp;lt;string&amp;gt;("in C#", 1, strs, strs2);
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;A common reason for explicitly specifying the type when calling a generic method occurs when class hierarchies are involved. For example, assume the following classes:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class A {
  // ...
}
class B: A {
  // ...
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Next, assuming the version of &lt;strong&gt;copyInsert( )&lt;/strong&gt; shown in the preceding program, you might try a sequence like the following to call &lt;strong&gt;copyInsert( )&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
B[] b = { new B(), new B(), new B() };
A[] a = new A[4];

// Insert an A into an array of B, copying to an A array.
ArrayUtils.copyInsert(new A(), 1, b, a); // Error, ambiguous!
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p class="para"&gt;Here, the compiler cannot infer what type should be substituted for &lt;strong&gt;T&lt;/strong&gt;. Should it be &lt;strong&gt;A&lt;/strong&gt; or &lt;strong&gt;B&lt;/strong&gt;? Remember, it is legal for a base class reference to refer to a derived class object. Thus, it is not inherently wrong to copy the contents of &lt;strong&gt;b&lt;/strong&gt; into &lt;strong&gt;a&lt;/strong&gt;. However, this works only if the type substituted for &lt;strong&gt;T&lt;/strong&gt; is &lt;strong&gt;A&lt;/strong&gt;, the base class. Unfortunately, the compiler doesn't know this.&lt;/p&gt;
&lt;p class="para"&gt;To fix the situation, simply explicitly specify the type, as shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
ArrayUtils.copyInsert&amp;lt;A&amp;gt;(new A(), 1, b, a); // Fixed!
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="last-para"&gt;Here, &lt;strong&gt;A&lt;/strong&gt; is explicitly substituted for &lt;strong&gt;T&lt;/strong&gt;, and the line compiles and runs without error.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/6929499622421123489/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-explicit-type-arguments-to-call.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6929499622421123489" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6929499622421123489" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/using-explicit-type-arguments-to-call.html" rel="alternate" title="Using Explicit Type Arguments to Call Generic Method" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-8968030586025211686</id><published>2008-10-25T01:09:00.001+05:30</published><updated>2008-10-27T19:24:32.001+05:30</updated><title type="text">Creating Simple Generic Method</title><content type="html">&lt;p class="first-para"&gt;As the preceding posts have shown, methods inside a generic class can make use of a class's type parameter and are, therefore, automatically generic relative to the type parameter. However, it is possible to declare a generic method that uses one or more type parameters of its own. Furthermore, it is possible to create a generic method that is enclosed within a non-generic class.&lt;/p&gt;
&lt;p class="para"&gt;Let's begin with an example. The following program declares a non-generic class called &lt;strong&gt;ArrayUtils&lt;/strong&gt; and a static generic method within that class called &lt;strong&gt;copyInsert( )&lt;/strong&gt;. The &lt;strong&gt;copyInsert( )&lt;/strong&gt; method copies the contents of one array to another, inserting a new element at a specified location in the process. It can be used with any type of array.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Demonstrate a generic method.

using System;

// A class of array utilities.  Notice that this is not
// a generic class.
class ArrayUtils {

  // Copy an array, inserting a new element
  // in the process.  This is a generic method.
  public static bool copyInsert&amp;lt;T&amp;gt;(T e, int idx,
                                   T[] src, T[] target) {

    // See if target array is big enough.
    if(target.Length &amp;lt; src.Length+1)
      return false;

    // Copy src to target, inserting e at idx in the process.
    for(int i=0, j=0; i &amp;lt; src.Length; i++, j++) {
      if(i == idx) {
        target[j] = e;
        j++;
      }
      target[j] = src[i];
    }

    return true;
  }
}

class GenMethDemo {
  public static void Main() {
    int[] nums = { 1, 2, 3 };
    int[] nums2 = new int[4];

    // Display contents of nums.
    Console.Write("Contents of nums: ");
    foreach(int x in nums)
      Console.Write(x + " ");

    Console.WriteLine();

    // Operate on an int array.
    ArrayUtils.copyInsert(99, 2, nums, nums2);

    // Display contents of nums2.
    Console.Write("Contents of nums2: ");
    foreach(int x in nums2)
      Console.Write(x + " ");

    Console.WriteLine();

    // Now, use copyInsert on an array of strings.
    string[] strs = { "Generics", "are", "powerful."};
    string[] strs2 = new string[4];

    // Display contents of strs.
    Console.Write("Contents of strs: ");
    foreach(string s in strs)
      Console.Write(s + " ");

    Console.WriteLine();

    // Insert into a string array.
    ArrayUtils.copyInsert("in C#", 1, strs, strs2);

    // Display contents of strs2.
    Console.Write("Contents of strs2: ");
    foreach(string s in strs2)
      Console.Write(s + " ");

    Console.WriteLine();

    // This call is invalid because the first argument
    // is of type double, and the third and fourth arguments
    // have base types of int.
//    ArrayUtils.copyInsert(0.01, 2, nums, nums2);

  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p class="para"&gt;The output from the program is shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Contents of nums: 1 2 3
Contents of nums2: 1 2 99 3
Contents of strs: Generics are powerful.
Contents of strs2: Generics in C# are powerful.
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Let's examine &lt;strong&gt;copyInsert( )&lt;/strong&gt; closely. First, notice how it is declared by this line:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
public static bool copyInsert&amp;lt;T&amp;gt;(T e, int idx,
                                 T[] src, T[] target) {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;The type parameter is declared &lt;em&gt;after&lt;/em&gt; the method name, but before the parameter list. Also notice that &lt;strong&gt;copyInsert( )&lt;/strong&gt; is static, enabling it to be called independently of any object. Understand, though, that generic methods can be either static or non-static. There is no restriction in this regard.&lt;/p&gt;
&lt;p class="para"&gt;Now, notice how &lt;strong&gt;copyInsert( )&lt;/strong&gt; is called within &lt;strong&gt;Main( )&lt;/strong&gt; by use of the normal call syntax, without the need to specify type arguments. This is because the types of the arguments are automatically discerned, and the type of &lt;strong&gt;T&lt;/strong&gt; is adjusted accordingly. This process is called &lt;em&gt;type inference.&lt;/em&gt; For example, in the first call:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
ArrayUtils.copyInsert(99, 2, nums, nums2);
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;the type of &lt;strong&gt;T&lt;/strong&gt; becomes &lt;strong&gt;int&lt;/strong&gt; because 99 and the base types of &lt;strong&gt;nums&lt;/strong&gt; and &lt;strong&gt;nums2&lt;/strong&gt; are &lt;strong&gt;int&lt;/strong&gt;. In the second call, &lt;strong&gt;string&lt;/strong&gt; types are used, and &lt;strong&gt;T&lt;/strong&gt; is replaced by &lt;strong&gt;string&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;Now, notice the commented-out code, shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
//    ArrayUtils.copyInsert(0.01, 2, nums, nums2);
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;If you remove the comment symbol and then try to compile the program, you will receive an error. The reason is that the type of the first argument is &lt;strong&gt;double&lt;/strong&gt;, but the base types of &lt;strong&gt;nums&lt;/strong&gt; and &lt;strong&gt;nums2&lt;/strong&gt; are &lt;strong&gt;int&lt;/strong&gt;. However, all three types must be substituted for the same type parameter, &lt;strong&gt;T&lt;/strong&gt;. This causes a type mismatch, which results in a compile-time error. This ability to enforce type safety is one of the most important advantages of generic methods.&lt;/p&gt;
&lt;p class="para"&gt;The syntax used to create &lt;strong&gt;copyInsert( )&lt;/strong&gt; can be generalized. Here is the general form of a generic method:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
&lt;em&gt;ret-type meth-name&lt;/em&gt;&amp;lt;&lt;em&gt;type-parameter-list&lt;/em&gt;&amp;gt;(&lt;em&gt;param-list&lt;/em&gt;) { // ...
&lt;/pre&gt;
&lt;p class="para"&gt;In all cases, &lt;em&gt;type-parameter-list&lt;/em&gt; is a comma-separated list of type parameters. Notice that for a generic method, the type parameter list follows the method name.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/8968030586025211686/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/creating-simple-generic-method.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/8968030586025211686" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/8968030586025211686" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/creating-simple-generic-method.html" rel="alternate" title="Creating Simple Generic Method" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-1079826038263698927</id><published>2008-10-25T00:34:00.001+05:30</published><updated>2008-10-25T00:34:58.711+05:30</updated><title type="text">Creating Default Object of Type Parameter</title><content type="html">&lt;p class="FIRST-PARA"&gt;When writing generic code, there will be times when the difference between value types and parameter types is an issue. One such situation occurs when you want to give an object of a type parameter a default value. For reference types, the default value is &lt;strong&gt;null&lt;/strong&gt;. For non-&lt;strong&gt;struct&lt;/strong&gt; value types, the default value is 0. The default value for a &lt;strong&gt;struct&lt;/strong&gt; is an object of that &lt;strong&gt;struct&lt;/strong&gt; with all fields set to their defaults. Thus, trouble occurs if you want to give a variable of a type parameter a default value. What value would you use-&lt;strong&gt;null&lt;/strong&gt;, 0, or something else? &lt;/p&gt;
&lt;p class="PARA"&gt;For example, given a generic class called &lt;strong&gt;Test&lt;/strong&gt; declared like this:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
class Test&amp;lt;T&amp;gt; {
  T obj;
  // ...
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;if you want to give &lt;strong&gt;obj&lt;/strong&gt; a default value, would you use&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
obj = null; // works only for reference types
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;or&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
obj = 0; // works only for numeric types and enums, but not structs
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p class="para"&gt;Neither approach works in all cases.&lt;/p&gt;
&lt;p class="PARA"&gt;The solution to this problem is to use another form of the &lt;strong&gt;default&lt;/strong&gt; keyword, shown here:&lt;/p&gt;
&lt;pre class="LITERALLAYOUT-NORMAL"&gt;
default(&lt;em&gt;type&lt;/em&gt;)
&lt;/pre&gt;
&lt;p class="para"&gt;This produces a default value of the specified &lt;em&gt;type,&lt;/em&gt; no matter what type is used. Thus, continuing with the example, to assign &lt;strong&gt;obj&lt;/strong&gt; a default value of type &lt;strong&gt;T&lt;/strong&gt;, you would use this statement:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
obj = default(T);
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;This will work for all type arguments, whether they are value or reference types.&lt;/p&gt;
&lt;p class="para"&gt;Here is a short program that demonstrates &lt;strong&gt;default&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
// Demonstrate the default keyword.

using System;

class MyClass {
  //...
}

// Construct a default object of T.
class Test&amp;lt;T&amp;gt; {
  public T obj;

  public Test() {
    // The following statement would work
    // only for reference types.
//    obj = null;

    // This statement works for both
    // reference and value types.
    obj = default(T);
  }

  // ...
}

class DefaultDemo {
  public static void Main() {
    // Construct Test using a reference type.
    Test&amp;lt;MyClass&amp;gt; x = new Test&amp;lt;MyClass&amp;gt;();

    if(x.obj == null)
      Console.WriteLine("x.obj is null.");

    // Construct Test using a value type.
    Test&amp;lt;int&amp;gt; y = new Test&amp;lt;int&amp;gt;();

    if(y.obj == 0)
      Console.WriteLine("y.obj is 0.");
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="PARA"&gt;The output is shown here:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;pre class="programlisting"&gt;
x.obj is null.
y.obj is 0.
&lt;/pre&gt;&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/1079826038263698927/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/creating-default-object-of-type.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1079826038263698927" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1079826038263698927" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/creating-default-object-of-type.html" rel="alternate" title="Creating Default Object of Type Parameter" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-6053062061673585299</id><published>2008-10-22T20:43:00.001+05:30</published><updated>2008-10-22T20:43:13.849+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Data Tables in C#"/><title type="text">Filtering &amp;amp; sorting DataTables with DataTable.Select()</title><content type="html">&lt;p&gt;&lt;span style="WORD-SPACING: 0px; FONT: 13px 'Trebuchet MS'; TEXT-TRANSFORM: none; COLOR: rgb(0,0,0); TEXT-INDENT: 0px; WHITE-SPACE: normal; LETTER-SPACING: normal; BORDER-COLLAPSE: separate; TEXT-ALIGN: left; orphans: 2; widows: 2; webkit-border-horizontal-spacing: 0px; webkit-border-vertical-spacing: 0px; webkit-text-decorations-in-effect: none; webkit-text-size-adjust: auto; webkit-text-stroke-width: 0" class="Apple-style-span"&gt;We all know that connections to databases from within our applications cost us processor cycles and thus time so it's a good idea to only 'talk' to your database when you really need too. In the .NET framework items like DataSets and DataTables etc. facilitate this to a large degree. In this post let's take the .Select() method of the &lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx" target="_blank"&gt;DataTable class&lt;/a&gt; as evidence of this.&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;.NET framework 2.0 DataTable.Select() method
&lt;br/&gt;&lt;/strong&gt;The DataTable.Select() method has four overloads and allows you to filter and display your rows in a number of ways in a manner similar to the way SQL does. The method can accept an expression string which although not nearly as powerful as full blown SQL does provide the advantage of not having to go back to the database to do simple things like showing records relevant to only a certain date range or a certain customer, product etc.&lt;/p&gt;
&lt;p&gt;Below is some of the valid expressions and filters you can pop into the Select() method to narrow your record set.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Standard Operator based expressions
&lt;br/&gt;&lt;/strong&gt;Things like &amp;gt;, &amp;lt;, &amp;gt;=, &amp;lt;=, =, &amp;lt;&amp;gt; are all supported of course. If your DataTable was called &lt;em&gt;salesStaff&lt;/em&gt; and you only wanted to return staff with &lt;em&gt;sales&lt;/em&gt; of greater than 100, you could do this with salesStaff.Select("sales &amp;gt; 100″). An array of DataRows will be returned, so depending on what you want to do with the results of the Select() method you may have to copy them back into another DataTable… more on that below.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;More SQL query like expressions
&lt;br/&gt;&lt;/strong&gt;Filtering by Like is also supported by the Select() method which I think is quite sweet. Wildcards as in SQL are * and %. Just like most variations of SQL support aggregate types so too does the Select() expression 'language'. Items like AVG, MIN, MAX, SUM and COUNT are all supported, so too are functions like LEN and SUBSTRING. If you need to test multple columns/conditions you can join them with the AND or OR operators &lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://support.microsoft.com/kb/891742" target="_blank"&gt;but be careful if your using .Net 1.1 SP 1 as there was a documented bug in .Select() when it was used with AND&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sorting with DataTable.Select()
&lt;br/&gt;&lt;/strong&gt;This is probabely the main way I use the Select() method. Its supported not via the expression parameter but via the sort parameter which is available in two overloaded .Select() methods. Its format is columnName asc/desc.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Importing DataTable.Select() method results into another DataTable
&lt;br/&gt;&lt;/strong&gt;Putting the results from a Select() query into another DataTable is often a requirement say for instance if you wanted to bind your results to a control. As mentioned above the Select() method returns an array of DataRows and since DataRows are the main building blocks of DataTables the process is very easy. Steps outlined are:&lt;/p&gt;
&lt;p&gt;&lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://msdn.microsoft.com/en-us/library/system.data.datatable.clone.aspx" target="_blank"&gt;Issue .Clone() your source DataTable to create a new DataTable with the same schema&lt;/a&gt;
&lt;br/&gt;
&lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://msdn.microsoft.com/en-us/library/system.data.datatable.select(VS.71).aspx" target="_blank"&gt;Issue .Select() on your source DataTable() to get an array of rows with the data you want&lt;/a&gt;
&lt;br/&gt;
&lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://msdn.microsoft.com/en-us/library/system.data.datatable.importrow.aspx" target="_blank"&gt;Loop through the DataRows array and issue .ImportRow() on your destination table each interation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and a code snippet to do the above might look something like the following:&lt;/p&gt;
&lt;blockquote style="PADDING-LEFT: 20px; MARGIN: 15px 30px 0px 10px; BORDER-LEFT: rgb(221,221,221) 5px solid"&gt;
&lt;p&gt;&lt;em&gt;//copy the schema of source table
&lt;br/&gt;
DataTable above24 = dt.Clone();
&lt;br/&gt;
&lt;br/&gt;
//get only the rows you want
&lt;br/&gt;
DataRow[] results = dt.Select("age &amp;gt; 24″);&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;//populate new destination table
&lt;br/&gt;
foreach (DataRow dr in results)
&lt;br/&gt;
above24.ImportRow(dr);&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;strong&gt;DataTable.Select() shortcomings
&lt;br/&gt;&lt;/strong&gt;The main things I don't like about the .Select() method is how you have to go through intermediary steps to get your results into another DataTable, why can't it just return another DataTable (which is directly bindable to a load of .NET data controls) and its lack of support for selecting distinct/unique rows which is often needed. As as note on that last one, it is possible to return distinct rows in a DataTable using &lt;a style="COLOR: rgb(34,34,156); TEXT-DECORATION: none" href="http://en.wikipedia.org/wiki/Language_Integrated_Query" target="_blank" title="LINQ"&gt;LINQ&lt;/a&gt;which is a .NET 3.5 component, however that topic might best be served with another post at a later date.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Can't I just use a DataView instead of calling DataTable.Select()?
&lt;br/&gt;&lt;/strong&gt;You can and DataViews are directly bindable to many controls too, however it is not always the best solution due to the generally accepted believe among many developers that .Select() is much faster than using the DataView equivalent of RowFilter (property). I regularly interchange between the two for a lot of small database projects, however for the projects where I need to be processing a mega amount of data I pretty much stick with .Select() 100% of the time as I reckon it provides real speed (as in seconds, not PC invisible micro time) advantages compared to DataViews.&lt;/p&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/Data+Tables+in+C%23" class="ztag" rel="tag"&gt;Data Tables in C#&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/6053062061673585299/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/filtering-sorting-datatables-with.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6053062061673585299" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6053062061673585299" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/filtering-sorting-datatables-with.html" rel="alternate" title="Filtering &amp;amp; sorting DataTables with DataTable.Select()" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-3226860030346921010</id><published>2008-10-22T20:32:00.001+05:30</published><updated>2008-10-22T20:32:18.986+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C# Generics"/><title type="text">Generic Structures</title><content type="html">&lt;p class="first-para"&gt;C# allows you to create generic structures. The syntax is the same as for generic classes. For example, in the following program, the &lt;strong&gt;XY&lt;/strong&gt; structure, which stores X, Y coordinates, is generic:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Demonstrate a generic struct.
using System;

// This structure is generic.
struct XY&amp;lt;T&amp;gt; {
  T x;
  T y;

  public XY(T a, T b) {
    x = a;
    y = b;
  }

  public T X {
    get { return x; }
    set { x = value; }
  }

  public T Y {
    get { return y; }
    set { y = value; }
  }

}

class StructTest {
  public static void Main() {
    XY&amp;lt;int&amp;gt; xy = new XY&amp;lt;int&amp;gt;(10, 20);
    XY&amp;lt;double&amp;gt; xy2 = new XY&amp;lt;double&amp;gt;(88.0, 99.0);
    Console.WriteLine(xy.X + ", " + xy.Y);

    Console.WriteLine(xy2.X + ", " + xy2.Y);
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;The output is shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
10, 20
88, 99
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Like generic classes, generic structures can have constraints. For example, this version of &lt;strong&gt;XY&lt;/strong&gt; restricts type arguments to value types:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
struct XY&amp;lt;T&amp;gt; where T : struct {
// ...
&lt;/pre&gt;&lt;/div&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/C%23+Generics" class="ztag" rel="tag"&gt;C# Generics&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/3226860030346921010/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-structures.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/3226860030346921010" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/3226860030346921010" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-structures.html" rel="alternate" title="Generic Structures" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-8117381711771850321</id><published>2008-10-22T20:31:00.001+05:30</published><updated>2008-10-22T20:31:18.436+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C# Generics"/><title type="text">General Form of a Generic Class</title><content type="html">&lt;p class="FIRST-PARA"&gt;The generics syntax shown in the preceding examples can be generalized. Here is the syntax for declaring a generic class:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
class &lt;em&gt;class-name&lt;/em&gt;&amp;lt;&lt;em&gt;type-param-list&lt;/em&gt;&amp;gt; { // ...
&lt;/pre&gt;
&lt;p class="PARA"&gt;Here is the syntax for declaring a reference to a generic class:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
&lt;em&gt;class-name&lt;/em&gt;&amp;lt;&lt;em&gt;type-arg-list&lt;/em&gt;&amp;gt; &lt;em&gt;var-name&lt;/em&gt; =
      new &lt;em&gt;class-name&lt;/em&gt;&amp;lt;&lt;em&gt;type-arg-list&lt;/em&gt;&amp;gt;(&lt;em&gt;cons-arg-list&lt;/em&gt;);
&lt;/pre&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/C%23+Generics" class="ztag" rel="tag"&gt;C# Generics&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/8117381711771850321/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/general-form-of-generic-class.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/8117381711771850321" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/8117381711771850321" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/general-form-of-generic-class.html" rel="alternate" title="General Form of a Generic Class" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-6703222772722158120</id><published>2008-10-22T20:25:00.001+05:30</published><updated>2008-10-22T20:25:08.126+05:30</updated><title type="text">Generic Class with Two Type Parameters</title><content type="html">&lt;p class="FIRST-PARA"&gt;You can declare more than one type parameter in a generic type. To specify two or more type parameters, simply use a comma-separated list. For example, the following &lt;strong&gt;TwoGen&lt;/strong&gt; class is a variation of the &lt;strong&gt;Gen&lt;/strong&gt; class that has two type parameters:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
// A simple generic class with two type
// parameters: T and V.

using System;
class TwoGen&amp;lt;T, V&amp;gt; {
  T ob1;
  V ob2;

  // Notice that this constructor has parameters
  // of type T and V.
  public TwoGen(T o1, V o2) {
    ob1 = o1;
    ob2 = o2;
  }

  // Show types of T and V.
  public void showTypes() {
    Console.WriteLine("Type of T is " + typeof(T));
    Console.WriteLine("Type of V is " + typeof(V));
  }

  public T getob1() {
    return ob1;
  }

  public V getob2() {
    return ob2;
  }
}

// Demonstrate two generic type parameters.
class SimpGen {
  public static void Main() {

    TwoGen&amp;lt;int, string&amp;gt; tgObj =
      new TwoGen&amp;lt;int, string&amp;gt;(119, "Alpha Beta Gamma");

    // Show the types.
    tgObj.showTypes();

    // Obtain and show values.
    int v = tgObj.getob1();
    Console.WriteLine("value: " + v);

    string str = tgObj.getob2();
    Console.WriteLine("value: " + str);
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="PARA"&gt;The output from this program is shown here:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;pre class="PROGRAMLISTING"&gt;
Type of T is System.Int32
Type of V is System.String
value: 119
value: Alpha Beta Gamma
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="PARA"&gt;Notice how &lt;strong&gt;TwoGen&lt;/strong&gt; is declared:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class TwoGen&amp;lt;T, V&amp;gt; {
&lt;/pre&gt;&lt;/div&gt;
&lt;p/&gt;
&lt;p class="PARA"&gt;It specifies two type parameters: &lt;strong&gt;T&lt;/strong&gt; and &lt;strong&gt;V&lt;/strong&gt;, separated by a comma. Because it has two type parameters, two type arguments must be passed to &lt;strong&gt;TwoGen&lt;/strong&gt; when an object is created, as shown next:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;pre class="programlisting"&gt;
TwoGen&amp;lt;int, string&amp;gt; tgObj =
  new TwoGen&amp;lt;int, string&amp;gt;(119, "Alpha Beta Gamma");
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="PARA"&gt;In this case, &lt;strong&gt;int&lt;/strong&gt; is substituted for &lt;strong&gt;T&lt;/strong&gt;, and &lt;strong&gt;string&lt;/strong&gt; is substituted for &lt;strong&gt;V&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="PARA"&gt;Although the two type arguments differ in this example, it is possible for both types to be the same. For example, the following line of code is valid:&lt;/p&gt;
&lt;div class="INFORMALEXAMPLE"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
TwoGen&amp;lt;string, string&amp;gt; x = new TwoGen&amp;lt;string, string&amp;gt;("Hello", "Goodbye");
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p class="last-para"&gt;In this case, both &lt;strong&gt;T&lt;/strong&gt; and &lt;strong&gt;V&lt;/strong&gt; would be of type &lt;strong&gt;string&lt;/strong&gt;. Of course, if the type arguments were always the same, then two type parameters would be unnecessary.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/6703222772722158120/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-class-with-two-type-parameters.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6703222772722158120" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6703222772722158120" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generic-class-with-two-type-parameters.html" rel="alternate" title="Generic Class with Two Type Parameters" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-946580561918895501</id><published>2008-10-22T20:23:00.001+05:30</published><updated>2008-10-22T20:23:56.787+05:30</updated><title type="text">How Generics Improve Type Safety</title><content type="html">&lt;p class="first-para"&gt;At this point you might be asking yourself the following question: Given that the same functionality found in the generic &lt;strong&gt;Gen&lt;/strong&gt; class can be achieved without generics, by simply specifying &lt;strong&gt;object&lt;/strong&gt; as the data type and employing the proper casts, what is the benefit of making &lt;strong&gt;Gen&lt;/strong&gt; generic? The answer is that generics automatically ensure the type safety of all operations involving &lt;strong&gt;Gen&lt;/strong&gt;. In the process, generics eliminate the need for you to use casts and to type-check code by hand.&lt;/p&gt;
&lt;p class="para"&gt;To understand the benefits of generics, first consider the following program that creates a non-generic equivalent of &lt;strong&gt;Gen&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// NonGen is functionally equivalent to Gen
// but does not use generics.

using System;

class NonGen {
  object ob; // ob is now of type object

  // Pass the constructor a reference of
  // type object.
  public NonGen(object o) {
    ob = o;
  }

  // Return type object.
  public object getob() {
    return ob;
  }

  // Show type of ob.
  public void showType() {
    Console.WriteLine("Type of ob is " + ob.GetType());
  }
}

// Demonstrate the non-generic class.
class NonGenDemo {
  public static void Main() {
    NonGen iOb;
    // Create NonGen object.
    iOb = new NonGen(102);

    // Show the type of data stored in iOb.
    iOb.showType();

    // Get the value in iOb.
    // This time, a cast is necessary.
    int v = (int) iOb.getob();
    Console.WriteLine("value: " + v);

    Console.WriteLine();

    // Create another NonGen object and
    // store a string in it.
    NonGen strOb = new NonGen("Non-Generics Test");

    // Show the type of data stored in strOb.
    strOb.showType();

    // Get the value of strOb.
    // Again, notice that a cast is necessary.
    String str = (string) strOb.getob();
    Console.WriteLine("value: " + str);

    // This compiles, but is conceptually wrong!
    iOb = strOb;

    // The following line results in a runtime exception.
    // v = (int) iOb.getob(); // runtime error!
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;This program produces the following output:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Type of ob is System.Int32
value: 102

Type of ob is System.String
value: Non-Generics Test
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;As you can see, the output is similar to the previous version of the program.&lt;/p&gt;
&lt;p class="para"&gt;There are several things of interest in this version. First, notice that &lt;strong&gt;NonGen&lt;/strong&gt; replaces all uses of &lt;strong&gt;T&lt;/strong&gt; with &lt;strong&gt;object&lt;/strong&gt;. This makes &lt;strong&gt;NonGen&lt;/strong&gt; able to store any type of object, as can the generic version. However, it also prevents the compiler from having any real knowledge about the type of data actually stored in &lt;strong&gt;NonGen&lt;/strong&gt;, which is bad for two reasons. First, explicit casts must be employed to retrieve the stored data. Second, many kinds of type mismatch errors cannot be found until runtime. Let's look closely at each problem.&lt;/p&gt;
&lt;p class="para"&gt;First, notice this line:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
int v = (int) iOb.getob();
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Because the return type of &lt;strong&gt;getob( )&lt;/strong&gt; is now &lt;strong&gt;object&lt;/strong&gt;, the cast to &lt;strong&gt;int&lt;/strong&gt; is necessary to enable the value returned by &lt;strong&gt;getob( )&lt;/strong&gt; to be unboxed and stored in &lt;strong&gt;v&lt;/strong&gt;. If you remove the cast, the program will not compile. In the generic version of the program, this cast was not needed because &lt;strong&gt;int&lt;/strong&gt; was passed as a type argument when &lt;strong&gt;iOb&lt;/strong&gt; was constructed. In the non-generic version, the cast must be employed. This is not only an inconvenience, but a potential source of error.&lt;/p&gt;
&lt;p class="para"&gt;Now, consider the following sequence from near the end of the program:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// This compiles, but is conceptually wrong!
iOb = strOb;

// The following line results in a runtime exception.
// v = (int) iOb.getob(); // runtime error!
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Here, &lt;strong&gt;strOb&lt;/strong&gt; is assigned to &lt;strong&gt;iOb&lt;/strong&gt;. However, &lt;strong&gt;strOb&lt;/strong&gt; refers to an object that contains a string, not an integer. This assignment is syntactically valid because all &lt;strong&gt;NonGen&lt;/strong&gt; references are the same, and any &lt;strong&gt;NonGen&lt;/strong&gt; reference can refer to any other &lt;strong&gt;NonGen&lt;/strong&gt; object. However, the statement is semantically wrong, as the commented-out line shows. In that line, the return type of &lt;strong&gt;getob( )&lt;/strong&gt; is cast to &lt;strong&gt;int&lt;/strong&gt;, and then an attempt is made to assign this value to &lt;strong&gt;v&lt;/strong&gt;. The trouble is that &lt;strong&gt;iOb&lt;/strong&gt; now refers to an object that stores a &lt;strong&gt;string&lt;/strong&gt;, not an &lt;strong&gt;int&lt;/strong&gt;. Unfortunately, without use of generics, the compiler has no way to know this. Instead, a runtime exception will occur when the cast to &lt;strong&gt;int&lt;/strong&gt; is attempted. To see this for yourself, try removing the comment symbol from the start of the line, and then compiling and running the program. A runtime error will occur.&lt;/p&gt;
&lt;p class="para"&gt;The preceding sequence can't occur when generics are used. If this sequence were attempted in the generic version of the program, the compiler would catch it and report an error, thus preventing a serious bug that results in a runtime exception. The ability to create type-safe code in which type-mismatch errors are caught at compile time is a key advantage of generics. Although using &lt;strong&gt;object&lt;/strong&gt; references to create "generic" code has always been possible in C#, that code was not type-safe, and its misuse could result in runtime exceptions. Generics prevent this from occurring. In essence, through generics, what were once runtime errors have become compile-time errors. This is a major advantage.&lt;/p&gt;
&lt;p class="para"&gt;There is one other point of interest in the &lt;strong&gt;NonGen&lt;/strong&gt; program. Notice how the type of the &lt;strong&gt;NonGen&lt;/strong&gt; instance variable &lt;strong&gt;ob&lt;/strong&gt; is obtained by &lt;strong&gt;showType( )&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Console.WriteLine("Type of ob is " + ob.GetType());
&lt;/pre&gt;&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/946580561918895501/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/how-generics-improve-type-safety.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/946580561918895501" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/946580561918895501" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/how-generics-improve-type-safety.html" rel="alternate" title="How Generics Improve Type Safety" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-6387807248653796297</id><published>2008-10-22T20:17:00.001+05:30</published><updated>2008-10-22T20:17:32.341+05:30</updated><title type="text">Generics Means?</title><content type="html">&lt;p class="first-para"&gt;At its core, the term &lt;em&gt;generics&lt;/em&gt; means &lt;em&gt;parameterized types.&lt;/em&gt; Parameterized types are important because they enable you to create classes, interfaces, methods, and delegates in which the type of data operated on is specified as a parameter. Using generics, it is possible to create a single class, for example, that automatically works with different types of data. A class, interface, method, or delegate that operates on a parameterized type is called &lt;em&gt;generic,&lt;/em&gt; as in &lt;em&gt;generic class&lt;/em&gt; or &lt;em&gt;generic method.&lt;/em&gt;&lt;/p&gt;
&lt;p class="para"&gt;It is important to understand that C# has always given you the ability to create generalized classes, interfaces, methods, and delegates by operating through references of type &lt;strong&gt;object&lt;/strong&gt;. Because &lt;strong&gt;object&lt;/strong&gt; is the base class of all other classes, an &lt;strong&gt;object&lt;/strong&gt; reference can refer to any type object. Thus, in pre-generics code, generalized code used &lt;strong&gt;object&lt;/strong&gt; references to operate on a variety of different types of objects. The problem was that it could not do so with type safety.&lt;/p&gt;
&lt;p class="para"&gt;Generics add the type safety that was lacking. They also streamline the process because it is no longer necessary to employ casts to translate between &lt;strong&gt;object&lt;/strong&gt; and the type of data that is actually being operated upon. Thus, generics expand your ability to reuse code and let you do so safely and easily. &lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/6387807248653796297/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generics-means.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6387807248653796297" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/6387807248653796297" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/generics-means.html" rel="alternate" title="Generics Means?" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-978614891196386475</id><published>2008-10-22T20:15:00.000+05:30</published><updated>2008-10-22T20:16:10.418+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C# Generics"/><title type="text">Simple Generics Example</title><content type="html">&lt;p class="first-para"&gt;Let's begin with a simple example of a generic class. The following program defines two classes. The first is the generic class &lt;strong&gt;Gen&lt;/strong&gt;, and the second is &lt;strong&gt;GenDemo&lt;/strong&gt;, which uses &lt;strong&gt;Gen&lt;/strong&gt;.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// A simple generic class.

using System;

// In the following Gen class, T is a type
// parameter that will be replaced by a real
// type when an object of type Gen is created.
class Gen&amp;lt;T&amp;gt; {
  T ob; // declare an object of type T

  // Notice that this constructor has a parameter of type T.
  public Gen(T o) {
    ob = o;
  }

  // Return ob, which is of type T.
  public T getob() {
    return ob;
  }

  // Show type of T.
  public void showType() {
    Console.WriteLine("Type of T is " + typeof(T));
  }
}

// Demonstrate the generic class.
class GenDemo {
  public static void Main() {
    // Create a Gen reference for int.
    Gen&amp;lt;int&amp;gt; iOb;

    // Create a Gen&amp;lt;int&amp;gt; object and assign its
    // reference to iOb.
    iOb = new Gen&amp;lt;int&amp;gt;(102);

    // Show the type of data used by iOb.
    iOb.showType();

    // Get the value in iOb.
    int v = iOb.getob();
    Console.WriteLine("value: " + v);

    Console.WriteLine();
    // Create a Gen object for strings.
    Gen&amp;lt;string&amp;gt; strOb = new Gen&amp;lt;string&amp;gt;("Generics add power.");
    
    // Show the type of data stored in strOb.
    strOb.showType();
    
    // Get the value in strOb.
    string str = strOb.getob();
    Console.WriteLine("value: " + str);
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;p class="para"&gt;The output produced by the program is shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Type of T is System.Int32
value: 102

Type of T is System.String
value: Generics add power.
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Let's examine this program carefully.&lt;/p&gt;
&lt;p class="para"&gt;First, notice how &lt;strong&gt;Gen&lt;/strong&gt; is declared by the following line:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
class Gen&amp;lt;T&amp;gt; {
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Here, &lt;strong&gt;T&lt;/strong&gt; is the name of a &lt;em&gt;type parameter.&lt;/em&gt; This name is used as a placeholder for the actual type that will be passed to &lt;strong&gt;Gen&lt;/strong&gt; when an object is created. Thus, &lt;strong&gt;T&lt;/strong&gt; is used within &lt;strong&gt;Gen&lt;/strong&gt; whenever the type parameter is needed. Notice that &lt;strong&gt;T&lt;/strong&gt; is contained within &lt;strong&gt;&amp;lt; &amp;gt;&lt;/strong&gt;. This syntax can be generalized. Whenever a type parameter is being declared, it is specified within angle brackets. Because &lt;strong&gt;Gen&lt;/strong&gt; uses a type parameter, &lt;strong&gt;Gen&lt;/strong&gt; is a &lt;em&gt;generic class.&lt;/em&gt;&lt;/p&gt;
&lt;p class="para"&gt;In the declaration of &lt;strong&gt;Gen&lt;/strong&gt;, there is no special significance to the name &lt;strong&gt;T&lt;/strong&gt;. Any valid identifier could have been used, but &lt;strong&gt;T&lt;/strong&gt; is traditional. Other commonly used type parameter names include &lt;strong&gt;V&lt;/strong&gt; and &lt;strong&gt;E&lt;/strong&gt;. Of course, you can also use descriptive names for type parameters, such as &lt;strong&gt;TValue&lt;/strong&gt; or &lt;strong&gt;TKey&lt;/strong&gt;. When using a descriptive name, it is common practice to use &lt;strong&gt;T&lt;/strong&gt; as the first letter.&lt;/p&gt;
&lt;p class="para"&gt;Next, &lt;strong&gt;T&lt;/strong&gt; is used to declare a variable called &lt;strong&gt;ob&lt;/strong&gt;, as shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
T ob; // declare an object of type T
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;As explained, &lt;strong&gt;T&lt;/strong&gt; is a placeholder for the actual type that will be specified when a &lt;strong&gt;Gen&lt;/strong&gt; object is created. Thus, &lt;strong&gt;ob&lt;/strong&gt; will be a variable of the type passed to &lt;strong&gt;T&lt;/strong&gt;. For example, if type &lt;strong&gt;string&lt;/strong&gt; is passed to &lt;strong&gt;T&lt;/strong&gt;, then in that instance, &lt;strong&gt;ob&lt;/strong&gt; will be of type &lt;strong&gt;string&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;Now consider &lt;strong&gt;Gen&lt;/strong&gt;'s constructor:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
public Gen(T o) {
  ob = o;
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Notice that its parameter, &lt;strong&gt;o&lt;/strong&gt;, is of type &lt;strong&gt;T&lt;/strong&gt;. This means that the actual type of &lt;strong&gt;o&lt;/strong&gt; is determined by the type passed to &lt;strong&gt;T&lt;/strong&gt; when a &lt;strong&gt;Gen&lt;/strong&gt; object is created. Also, because both the parameter &lt;strong&gt;o&lt;/strong&gt; and the instance variable &lt;strong&gt;ob&lt;/strong&gt; are of type &lt;strong&gt;T&lt;/strong&gt;, they will both be of the same actual type when a &lt;strong&gt;Gen&lt;/strong&gt; object is created. &lt;/p&gt;
&lt;p class="para"&gt;The type parameter &lt;strong&gt;T&lt;/strong&gt; can also be used to specify the return type of a method, as is the case with the &lt;strong&gt;getob( )&lt;/strong&gt; method, shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
public T getob() {
  return ob;
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Because &lt;strong&gt;ob&lt;/strong&gt; is also of type &lt;strong&gt;T&lt;/strong&gt;, its type is compatible with the return type specified by &lt;strong&gt;getob( )&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;The &lt;strong&gt;showType( )&lt;/strong&gt; method displays the type of &lt;strong&gt;T&lt;/strong&gt; by passing &lt;strong&gt;T&lt;/strong&gt; to the &lt;strong&gt;typeof&lt;/strong&gt; operator. Because a real type will be substituted for &lt;strong&gt;T&lt;/strong&gt; when an object of type &lt;strong&gt;Gen&lt;/strong&gt; is created, &lt;strong&gt;typeof&lt;/strong&gt; will obtain type information about the actual type.&lt;/p&gt;
&lt;p class="para"&gt;The &lt;strong&gt;GenDemo&lt;/strong&gt; class demonstrates the generic &lt;strong&gt;Gen&lt;/strong&gt; class. It first creates a version of &lt;strong&gt;Gen&lt;/strong&gt; for type &lt;strong&gt;int&lt;/strong&gt;, as shown here:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Gen&amp;lt;int&amp;gt; iOb;
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Look closely at this declaration. First, notice that the type &lt;strong&gt;int&lt;/strong&gt; is specified within the angle brackets after &lt;strong&gt;Gen&lt;/strong&gt;. In this case, &lt;strong&gt;int&lt;/strong&gt; is a &lt;em&gt;type argument&lt;/em&gt; that is passed to &lt;strong&gt;Gen&lt;/strong&gt;'s type parameter, &lt;strong&gt;T&lt;/strong&gt;. This creates a version of &lt;strong&gt;Gen&lt;/strong&gt; in which all uses of &lt;strong&gt;T&lt;/strong&gt; are replaced by &lt;strong&gt;int&lt;/strong&gt;. Thus, for this declaration, &lt;strong&gt;ob&lt;/strong&gt; is of type &lt;strong&gt;int&lt;/strong&gt;, and the return type of &lt;strong&gt;getob( )&lt;/strong&gt; is of type &lt;strong&gt;int&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;When you pass a type argument to a generic class, you are creating what is referred to in C# as a &lt;em&gt;closed constructed type.&lt;/em&gt; (The term &lt;em&gt;closed&lt;/em&gt; indicates that a type argument has been specified.) Thus, &lt;strong&gt;Gen&amp;lt;int&amp;gt;&lt;/strong&gt; is a closed constructed type. In essence, a generic type, such as &lt;strong&gt;Gen&amp;lt;T&amp;gt;&lt;/strong&gt;, is an abstraction. It is only after a specific version, such as &lt;strong&gt;Gen&amp;lt;int&amp;gt;&lt;/strong&gt;, has been constructed that a concrete type has been created. In C# terminology, a construct such as &lt;strong&gt;Gen&amp;lt;T&amp;gt;&lt;/strong&gt; is called an &lt;em&gt;open constructed type,&lt;/em&gt; because no type argument has been specified.&lt;/p&gt;
&lt;p class="para"&gt;The next line assigns to &lt;strong&gt;iOb&lt;/strong&gt; a reference to an instance of an &lt;strong&gt;int&lt;/strong&gt; version of the &lt;strong&gt;Gen&lt;/strong&gt; class:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
iOb = new Gen&amp;lt;int&amp;gt;(102);
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Notice that when the &lt;strong&gt;Gen&lt;/strong&gt; constructor is called, the type argument &lt;strong&gt;int&lt;/strong&gt; is also specified. This is necessary because the type of the object (in this case &lt;strong&gt;iOb&lt;/strong&gt;) to which the reference is being assigned is of type &lt;strong&gt;Gen&amp;lt;int&amp;gt;&lt;/strong&gt;. Thus, the reference returned by &lt;strong&gt;new&lt;/strong&gt; must also be of type &lt;strong&gt;Gen&amp;lt;int&amp;gt;&lt;/strong&gt;. If it isn't, a compile-time error will result. For example, the following assignment will cause a compile-time error:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
iOb = new Gen&amp;lt;double&amp;gt;(118.12); // Error!
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Because &lt;strong&gt;iOb&lt;/strong&gt; is of type &lt;strong&gt;Gen&amp;lt;int&amp;gt;&lt;/strong&gt;, it can't be used to refer to an object of &lt;strong&gt;Gen&amp;lt;double&amp;gt;&lt;/strong&gt;. This type checking is one of the main benefits of generics because it ensures type safety.&lt;/p&gt;
&lt;p class="para"&gt;The program then displays the type of &lt;strong&gt;ob&lt;/strong&gt; within &lt;strong&gt;iOb&lt;/strong&gt;, which is &lt;strong&gt;System.Int32&lt;/strong&gt;. This is the .NET class that corresponds to &lt;strong&gt;int&lt;/strong&gt;. Next, the program obtains the value of &lt;strong&gt;ob&lt;/strong&gt; by use of the following line:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
int v = iOb.getob();
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Because the return type of &lt;strong&gt;getob( )&lt;/strong&gt; is &lt;strong&gt;T&lt;/strong&gt;, which was replaced by &lt;strong&gt;int&lt;/strong&gt; when &lt;strong&gt;iOb&lt;/strong&gt; was declared, the return type of &lt;strong&gt;getob( )&lt;/strong&gt; is also &lt;strong&gt;int&lt;/strong&gt;. Thus, this value can be assigned to an &lt;strong&gt;int&lt;/strong&gt; variable.&lt;/p&gt;
&lt;p class="para"&gt;Next, &lt;strong&gt;GenDemo&lt;/strong&gt; declares an object of type &lt;strong&gt;Gen&amp;lt;string&amp;gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Gen&amp;lt;string&amp;gt; strOb = new Gen&amp;lt;string&amp;gt;("Generics add power.");
&lt;/pre&gt;&lt;/div&gt;
&lt;p/&gt;
&lt;p class="para"&gt;Because the type argument is &lt;strong&gt;string&lt;/strong&gt;, &lt;strong&gt;string&lt;/strong&gt; is substituted for &lt;strong&gt;T&lt;/strong&gt; inside &lt;strong&gt;Gen&lt;/strong&gt;. This creates a &lt;strong&gt;string&lt;/strong&gt; version of &lt;strong&gt;Gen&lt;/strong&gt;, as the remaining lines in the program demonstrate.&lt;/p&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/C%23+Generics" class="ztag" rel="tag"&gt;C# Generics&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/978614891196386475/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/simple-generics-example.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/978614891196386475" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/978614891196386475" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/simple-generics-example.html" rel="alternate" title="Simple Generics Example" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-7273032134609557465</id><published>2008-10-20T17:20:00.001+05:30</published><updated>2008-10-20T17:20:18.826+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="SQL in C#"/><title type="text">C# Executing SQL Command or Stored Procedure</title><content type="html">&lt;p class="first-para"&gt;The &lt;em&gt;IDbCommand&lt;/em&gt; interface represents a database command, and each data provider includes a unique implementation. Here is the list of &lt;em&gt;IDbCommand&lt;/em&gt; implementations for the five standard data providers.&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.Odbc.OdbcCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OleDb.OleDbCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OracleClient.OracleCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlServerCe.SqlCeCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlClient.SqlCommand&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;To execute a command against a database you must have an open connection and a properly configured command object appropriate to the type of database you are accessing. You can create command objects directly using a constructor, but a simpler approach is to use the &lt;em&gt;CreateCommand&lt;/em&gt; factory method of a connection object. The &lt;em&gt;CreateCommand&lt;/em&gt; method returns a command object of the correct type for the data provider and configures it with basic information obtained from the connection you used to create the command. Before executing the command, you must configure the properties described in the below table which are common to all command implementations.&lt;/p&gt;
&lt;table width="90%" style="MARGIN-LEFT: 10px" border="1" class="table"&gt;
&lt;caption class="table-title"&gt;&lt;span class="table-title"&gt;&lt;span class="table-titlelabel"&gt;Table 10.3:&lt;/span&gt; Common Command Object Properties&lt;/span&gt;&lt;/caption&gt;
&lt;thead&gt;
&lt;tr valign="top"&gt;
&lt;th scope="col" align="left" class="th" width="23%"&gt;
&lt;p class="table-para"&gt;Property&lt;/p&gt;
&lt;/th&gt;
&lt;th scope="col" align="left" class="th" width="77%"&gt;
&lt;p class="table-para"&gt;Description&lt;/p&gt;
&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandText&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;string&lt;/em&gt; containing the text of the SQL command to execute or the name of a stored procedure. The content of the &lt;em&gt;CommandText&lt;/em&gt; property must be compatible with the value you specify in the &lt;em&gt;CommandType&lt;/em&gt; property.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandTimeout&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;An &lt;em&gt;int&lt;/em&gt; that specifies the number of seconds to wait for the command to return before timing out and raising an exception. Defaults to 30 seconds.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;CommandType&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A value of the &lt;em&gt;System.Data.CommandType&lt;/em&gt; enumeration that specifies the type of command represented by the command object. For most data providers, valid values are &lt;em&gt;StoredProcedure&lt;/em&gt;, when you want to execute a stored procedure, and &lt;em&gt;Text&lt;/em&gt;, when you want to execute a SQL text command. If you are using the OLE DB Data Provider, you can specify &lt;em&gt;TableDirect&lt;/em&gt; when you want to return the entire contents of one or more tables; refer to the .NET Framework SDK documentation for more details. Defaults to &lt;em&gt;Text&lt;/em&gt;.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Connection&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;An &lt;em&gt;IDbConnection&lt;/em&gt; instance that provides the connection to the database on which you will execute the command. If you create the command using the &lt;em&gt;IDbConnection.CreateCommand&lt;/em&gt; method, this property will be automatically set to the &lt;em&gt;IDbConnection&lt;/em&gt; instance from which you created the command.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Parameters&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;System.Data.IDataParameterCollection&lt;/em&gt; instance containing the set of parameters to substitute into the command.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="23%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;&lt;em&gt;Transaction&lt;/em&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="77%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;A &lt;em&gt;System.Data.IDbTransaction&lt;/em&gt; instance representing the transaction into which to enlist the command. (See the .NET Framework SDK documentation for details about transactions.)&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p class="para"&gt;Once you have configured your command object, there are a number of ways to execute it depending on the nature of the command, the type of data returned by the command, and the format in which you want to process the data.&lt;/p&gt;
&lt;p class="para"&gt;To execute a command, such as &lt;strong&gt;INSERT&lt;/strong&gt;, &lt;strong&gt;DELETE&lt;/strong&gt;, or &lt;strong&gt;CREATE TABLE&lt;/strong&gt;, that doesn't return database data, call &lt;em&gt;ExecuteNonQuery&lt;/em&gt;. For the &lt;strong&gt;UPDATE&lt;/strong&gt;, &lt;strong&gt;INSERT&lt;/strong&gt;, and &lt;strong&gt;DELETE&lt;/strong&gt; commands, &lt;em&gt;ExecuteNonQuery&lt;/em&gt; method returns an &lt;em&gt;int&lt;/em&gt; that specifies the number of rows affected by the command. For other commands, such as &lt;strong&gt;CREATE TABLE&lt;/strong&gt;, &lt;em&gt;ExecuteNonQuery&lt;/em&gt; returns the value -1. Here is an example that uses &lt;strong&gt;UPDATE&lt;/strong&gt; to modify a record.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteNonQueryExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.Text;
    com.CommandText = "UPDATE Employees SET Title = 'Sales Director'" +
        " WHERE EmployeeId = '5'";

    // Execute the command and process the result.
    int result = com.ExecuteNonQuery();

    if (result == 1) {
        Console.WriteLine("Employee title updated.");
    } else {
        Console.WriteLine("Employee title not updated.");
    }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;To execute a command that returns a result set, such as a &lt;strong&gt;SELECT&lt;/strong&gt; statement or stored procedure, use the &lt;em&gt;ExecuteReader&lt;/em&gt; method. &lt;em&gt;ExecuteReader&lt;/em&gt; returns an &lt;em&gt;IDataReader&lt;/em&gt; instance through which you have access to the result data. Most data providers also allow you to execute multiple SQL commands in a single call to the &lt;em&gt;ExecuteReader&lt;/em&gt; method. This code excerpt uses the &lt;em&gt;ExecuteReader&lt;/em&gt; method to execute the Ten Most Expensive Products stored procedure from the Northwind database and display the results to the console.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteReaderExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.StoredProcedure;
    com.CommandText = "Ten Most Expensive Products";

    // Execute the command and process the results
    using (IDataReader reader = com.ExecuteReader()) {

        Console.WriteLine("Price of the Ten Most Expensive Products.");

        while (reader.Read()) {

            // Display the product details.
            Console.WriteLine("  {0} = {1}", 
                reader["TenMostExpensiveProducts"],
                reader["UnitPrice"]);
        }
    }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;If you want to execute a query but only need the value from the first column of the first row of result data, use the &lt;em&gt;ExecuteScalar&lt;/em&gt; method. The value is returned as an &lt;em&gt;object&lt;/em&gt; reference that you must cast to the correct type. Here is an example.&lt;/p&gt;
&lt;pre class="programlisting"&gt;
public static void ExecuteScalarExample(IDbConnection con) {

    // Create and configure a new command.
    IDbCommand com = con.CreateCommand();
    com.CommandType = CommandType.Text;
    com.CommandText = "SELECT COUNT(*) FROM Employees";

    // Execute the command and cast the result.
    int result = (int)com.ExecuteScalar();

    Console.WriteLine("Employee count = " + result);
}
&lt;/pre&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/SQL+in+C%23" class="ztag" rel="tag"&gt;SQL in C#&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/7273032134609557465/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-executing-sql-command-or-stored.html#comment-form" rel="replies" title="1 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7273032134609557465" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7273032134609557465" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-executing-sql-command-or-stored.html" rel="alternate" title="C# Executing SQL Command or Stored Procedure" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-7549328629951406380</id><published>2008-10-20T17:17:00.001+05:30</published><updated>2008-10-20T17:17:50.574+05:30</updated><title type="text">C# Connection Pooling</title><content type="html">&lt;p class="first-para"&gt;Connection pooling significantly reduces the overhead associated with creating and destroying database connections. Connection pooling also improves the scalability of solutions by reducing the number of concurrent connections a database must maintain-many of which sit idle for a significant portion of their lifetimes. With connection pooling, instead of creating and opening a new connection object whenever you need one, you take an already open connection from the connection pool. When you have finished using the connection, instead of closing it, you return it to the pool and allow other code to use it.&lt;/p&gt;
&lt;p class="para"&gt;The SQL Server and Oracle data providers encapsulate connection- pooling functionality that they enable by default. One connection pool exists for each unique connection string you specify when you open a new connection. Each time you open a new connection with a connection string that you have used previously, the connection is taken from the existing pool. Only if you specify a different connection string will the data provider create a new connection pool. You can control some characteristics of your pool using the connection string settings described in below table. Note that Once created, a pool exists until your process terminates.&lt;/p&gt;
&lt;table width="90%" style="MARGIN-LEFT: 10px" border="1" class="table"&gt;
&lt;caption class="table-title"&gt;&lt;span class="table-title"&gt;&lt;span class="table-titlelabel"&gt;Table 10.2:&lt;/span&gt; Connection String Settings That Control Connection Pooling&lt;/span&gt;&lt;/caption&gt;
&lt;thead&gt;
&lt;tr valign="top"&gt;
&lt;th scope="col" align="left" class="th" width="20%"&gt;
&lt;p class="table-para"&gt;Setting&lt;/p&gt;
&lt;/th&gt;
&lt;th scope="col" align="left" class="th" width="80%"&gt;
&lt;p class="table-para"&gt;Description&lt;/p&gt;
&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Connection Lifetime&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the maximum time in seconds that a connection is allowed to live in the pool before it's closed. The age of a connection is tested only when the connection is returned to the pool. This setting is useful for minimizing pool size if the pool isn't heavily used and also ensures optimal load balancing is achieved in clustered database environments. The default value is 0, which means connections exist for the life of the current process.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Connection Reset&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Supported only by the SQL Server data provider. Specifies whether connections are reset as they are taken from the pool. A value of "True" ensures a connection's state is reset but requires an additional communication with the database. The default value is "True".&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Max Pool Size&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the maximum number of connections that should be in the pool. Connections are created and added to the pool as required until this figure is reached. If a request for a connection is made but there are no free connections, the caller will block until a connection becomes available. The default value is 100.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Min Pool Size&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Specifies the minimum number of connections that should be in the pool. On pool creation, this number of connections are created and added to the pool. During periodic maintenance, or when a connection is requested, connections are added to the pool to ensure the minimum number of connections is available. The default value is 0.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr valign="top"&gt;
&lt;td width="20%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Pooling&lt;/p&gt;
&lt;/td&gt;
&lt;td width="80%" align="left" class="td"&gt;
&lt;p class="table-para"&gt;Set to "False" to obtain a non-pooled connection. The default value is "True".&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;This code excerpt from the sample code for this post demonstrates the configuration of a connection pool that contains a minimum of 5 and a maximum of 15 connections. Connections expire after 10 minutes (600 seconds) and are reset each time a connection is obtained from the pool.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Obtain a pooled connection.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;" +    // local SQL Server instance
        "Database = Northwind;" +       // the sample Northwind DB
        "Integrated Security = SSPI;" + // integrated Windows security
        "Min Pool Size = 5;" +          // configure minimum pool size
        "Max Pool Size = 15;" +         // configure maximum pool size
        "Connection Reset = True;" +    // reset connections each use
        "Connection Lifetime = 600";    // set maximum connection lifetime

    // Open the Database connection.
    con.Open();

    // Access the database...
    §

    // At the end of the using block, the Dispose calls Close, which
    // returns the connection to the pool for reuse.
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;This code excerpt demonstrates how to use the &lt;em&gt;Pooling&lt;/em&gt; setting to obtain a connection object that isn't from a pool. This is useful if your application uses a single long-lived connection to a database.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Obtain a non-pooled connection.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;" +    // local SQL Server instance
        "Database = Northwind;" +       // the sample Northwind DB
        "Integrated Security = SSPI;" + // integrated Windows security
        "Pooling = False";              // specify non-pooled connection

    // Open the Database connection.
    con.Open();

    // Access the database...
    

    // At the end of the using block, the Dispose calls Close, which
    // closes the non-pooled connection.
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="last-para"&gt;The ODBC and OLE DB data providers also support connection pooling, but they don't implement connection pooling within managed .NET classes and you don't configure the pool in the same way as for the SQL Server or Oracle data providers. ODBC connection pooling is managed by the ODBC Driver Manager and configured using the ODBC Data Source Administrator tool in the Control Panel. OLE DB connection pooling is managed by the native OLE DB implementation; the most you can do is disable pooling by including the setting &lt;span class="fixed"&gt;"OLE DB Services=-4;"&lt;/span&gt; in your connection string. The SQL Server CE data provider doesn't support connection pooling because SQL Server CE supports only a single concurrent connection.&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/7549328629951406380/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-connection-pooling.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7549328629951406380" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/7549328629951406380" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-connection-pooling.html" rel="alternate" title="C# Connection Pooling" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-591081051621227439</id><published>2008-10-20T17:14:00.001+05:30</published><updated>2008-10-20T17:14:53.291+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="Database Access in C#"/><title type="text">Connecting to DB</title><content type="html">&lt;p class="first-para"&gt;The first step in database access is to open a connection to the database. The &lt;em&gt;IDbConnection&lt;/em&gt; interface represents a database connection, and each data provider includes a unique implementation. Here is the list of &lt;em&gt;IDbConnection&lt;/em&gt; implementations for the five standard data providers.&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.Odbc.OdbcConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OleDb.OleDbConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.OracleClient.OracleConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlServerCe.SqlCeConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;&lt;em&gt;System.Data.SqlClient.SqlConnection&lt;/em&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;You configure a connection object using a connection string. A connection string is a set of semicolon-separated name value pairs. You can supply a connection string either as a constructor argument or by setting a connection object's &lt;em&gt;ConnectionString&lt;/em&gt; property before opening the connection. Each connection class implementation requires that you provide different information in the connection string. Refer to the &lt;em&gt;ConnectionString&lt;/em&gt; property documentation for each implementation to see the values you can specify. Possible settings include the following:&lt;/p&gt;
&lt;ul class="itemizedlist"&gt;
&lt;li class="first-listitem"&gt;
&lt;p class="first-para"&gt;The name of the target database server&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;The name of the database to open initially&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Connection timeout values&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Connection-pooling behavior&lt;/p&gt;
&lt;/li&gt;
&lt;li class="listitem"&gt;
&lt;p class="first-para"&gt;Authentication mechanisms to use when connecting to secured databases, including provision of user names and passwords&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p class="para"&gt;Once configured, call the connection object's &lt;em&gt;Open&lt;/em&gt; method to open the connection to the database. You can then use the connection object to execute commands against the data source. The properties of a connection object also allow you to retrieve information about the state of a connection and the settings used to open the connection. When you're finished with a connection, you should always call its &lt;em&gt;Close&lt;/em&gt; method to free up the underlying database connection and system resources. &lt;em&gt;IDbConnection&lt;/em&gt; extends &lt;em&gt;System.IDisposable&lt;/em&gt;, meaning that each connection class implements the &lt;em&gt;Dispose&lt;/em&gt; method. &lt;em&gt;Dispose&lt;/em&gt; automatically calls &lt;em&gt;Close&lt;/em&gt;, making the &lt;em&gt;using&lt;/em&gt; statement a very clean and efficient way of using connection objects in your code.&lt;/p&gt;
&lt;p class="para"&gt;You achieve optimum scalability by opening your database connection as late as possible and closing it again as soon as you have finished. This ensures that you don't tie up database connections for long periods and give all code the maximum opportunity to obtain a connection. This is especially important if you are using connection pooling.&lt;/p&gt;
&lt;p class="para"&gt;The code shown here demonstrates how to use the &lt;em&gt;SqlConnection&lt;/em&gt; class to open a connection to a SQL Server database running on the local machine that uses integrated Windows security. To access a remote machine, simply change the data source name from &lt;em&gt;localhost&lt;/em&gt; to the name of your database instance.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Create an empty SqlConnection object.
using (SqlConnection con = new SqlConnection()) {

    // Configure the SqlConnection object's connection string.
    con.ConnectionString = 
        "Data Source = localhost;"+ // local SQL Server instance
        "Database = Northwind;" +   // the sample Northwind DB
        "Integrated Security=SSPI"; // integrated Windows security

    // Open the Database connection.
    con.Open();

    // Display information about the connection.
    if (con.State == ConnectionState.Open) {
        Console.WriteLine("SqlConnection Information:");
        Console.WriteLine("  Connection State = " + con.State);
        Console.WriteLine("  Connection String = " + 
            con.ConnectionString);
        Console.WriteLine("  Database Source = " + con.DataSource);
        Console.WriteLine("  Database = " + con.Database);
        Console.WriteLine("  Server Version = " + con.ServerVersion);
        Console.WriteLine("  Workstation Id = " + con.WorkstationId);
        Console.WriteLine("  Timeout = " + con.ConnectionTimeout);
        Console.WriteLine("  Packet Size = " + con.PacketSize);
    } else {
        Console.WriteLine("SqlConnection failed to open.");
        Console.WriteLine("  Connection State = " + con.State);
    }
    // At the end of the using block Dispose() calls Close().
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;As another example, the following excerpt from the sample code for this recipe shows the connection string used to open a connection to the same database if you were using the OLE DB data provider to provide connectivity.&lt;/p&gt;
&lt;div class="widecontent"&gt;
&lt;pre class="programlisting"&gt;
// Create an empty OleDbConnection object.
using (OleDbConnection con = new OleDbConnection()) {

    // Configure the OleDbConnection object's connection string.
    con.ConnectionString = 
        "Provider = SQLOLEDB;" +         // OLE DB Provider for SQL Server
        "Data Source = localhost;" +     // local SQL Server instance
        "Initial Catalog = Northwind;" + // the sample Northwind DB
        "Integrated Security=SSPI";      // integrated Windows security

    // Open the Database connection.
    con.Open();
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/Database+Access+in+C%23" class="ztag" rel="tag"&gt;Database Access in C#&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/591081051621227439/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/connecting-to-db.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/591081051621227439" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/591081051621227439" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/connecting-to-db.html" rel="alternate" title="Connecting to DB" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-5240107523943415718</id><published>2008-10-16T11:58:00.001+05:30</published><updated>2008-10-16T11:58:39.112+05:30</updated><title type="text">How to Implement IComparable in C#</title><content type="html">&lt;div class="section"&gt;
&lt;h3 class="sect3-title"&gt;Implementing IComparable for Non-Generic Collections&lt;/h3&gt;
&lt;p class="first-para"&gt;If you want to sort objects that are stored in a non-generic collection, then you will implement the non-generic version of &lt;strong&gt;IComparable&lt;/strong&gt;. It defines only one method, &lt;strong&gt;CompareTo( )&lt;/strong&gt;, which determines how comparisons are performed. The general form of &lt;strong&gt;CompareTo( )&lt;/strong&gt; is shown here:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
int Compare To(object &lt;em&gt;obj&lt;/em&gt;)
&lt;/pre&gt;
&lt;p class="para"&gt;&lt;strong&gt;Compare To( )&lt;/strong&gt; compares the invoking object to &lt;em&gt;obj.&lt;/em&gt; To sort in ascending order, your implementation must return zero if the objects are equal, a positive value if the invoking object is greater than &lt;em&gt;obj,&lt;/em&gt; and a negative value if the invoking object is less than &lt;em&gt;obj.&lt;/em&gt; You can sort in descending order by reversing the outcome of the comparison. The method can throw an &lt;strong&gt;ArgumentException&lt;/strong&gt; if the type of &lt;em&gt;obj&lt;/em&gt; is not compatible for comparison with the invoking object.&lt;/p&gt;
&lt;p class="para"&gt;Here is an example that shows how to implement &lt;strong&gt;IComparable&lt;/strong&gt;. It adds &lt;strong&gt;IComparable&lt;/strong&gt; to the &lt;strong&gt;Inventory&lt;/strong&gt; class developed in the preceding section. By implementing &lt;strong&gt;IComparable&lt;/strong&gt;, it allows a collection of &lt;strong&gt;Inventory&lt;/strong&gt; objects to be sorted, as the program illustrates.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Implement IComparable.

using System;
using System.Collections;

// Implement the non-generic IComparable interface.
class Inventory : IComparable {
  string name;
  double cost;
  int onhand;

  public Inventory(string n, double c, int h) {
    name = n;
    cost = c;
    onhand = h;
  }
  public override string ToString() {
    return
      String.Format("{0,-10}Cost: {1,6:C}  On hand: {2}",
                    name, cost, onhand);
  }

  // Implement the IComparable interface.
  public int Compare To(object obj) {
    Inventory b;
    b = (Inventory) obj;
    return name.CompareTo(b.name);
  }
}

class IComparableDemo {
  public static void Main() {
    ArrayList inv = new ArrayList();

    // Add elements to the list
    inv.Add(new Inventory("Pliers", 5.95, 3));
    inv.Add(new Inventory("Wrenches", 8.29, 2));
    inv.Add(new Inventory("Hammers", 3.50, 4));
    inv.Add(new Inventory("Drills", 19.88, 8));

    Console.WriteLine("Inventory list before sorting:");
    foreach(Inventory i in inv) {
      Console.WriteLine("   " + i);
    }
    Console.WriteLine();

    // Sort the list.
    inv.Sort();

    Console.WriteLine("Inventory list after sorting:");
    foreach(Inventory i in inv) {
      Console.WriteLine("   " + i);
    }
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="para"&gt;Here is the output. Notice that after the call to &lt;strong&gt;Sort( )&lt;/strong&gt;, the inventory is sorted by name.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
Inventory list before sorting:
   Pliers    Cost:  $5.95  On hand: 3
   Wrenches  Cost:  $8.29  On hand: 2
   Hammers   Cost:  $3.50  On hand: 4
   Drills    Cost: $19.88  On hand: 8

Inventory list after sorting:
   Drills    Cost: $19.88  On hand: 8
   Hammers   Cost:  $3.50  On hand: 4
   Pliers    Cost:  $5.95  On hand: 3
   Wrenches  Cost:  $8.29  On hand: 2
&lt;/pre&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class="section"&gt;
&lt;h3 class="sect3-title"&gt;Implementing IComparable&amp;lt;T&amp;gt; for Generic Collections&lt;/h3&gt;
&lt;p class="first-para"&gt;If you want to sort objects that are stored in a generic collection, then you will implement &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt;. This version defines the generic form of &lt;strong&gt;CompareTo( )&lt;/strong&gt; as shown here:&lt;/p&gt;
&lt;pre class="literallayout-normal"&gt;
int CompareTo(T &lt;em&gt;obj&lt;/em&gt;)
&lt;/pre&gt;
&lt;p class="para"&gt;&lt;strong&gt;CompareTo( )&lt;/strong&gt; compares the invoking object to &lt;em&gt;obj.&lt;/em&gt; Notice that &lt;em&gt;obj&lt;/em&gt; is of type &lt;strong&gt;T&lt;/strong&gt;. To sort in ascending order, your implementation must return zero if the objects are equal, a positive value if the invoking object is greater than &lt;em&gt;obj,&lt;/em&gt; and a negative value if the invoking object is less than &lt;em&gt;obj.&lt;/em&gt; To sort in descending order, reverse the outcome of the comparison. When implementing &lt;strong&gt;Icomparable&amp;lt;T&amp;gt;&lt;/strong&gt;, you will usually pass the type name of the implementing class as a type argument.&lt;/p&gt;
&lt;p class="para"&gt;The following example reworks the preceding program so that it uses &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt;. Notice that it uses the generic &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt; collection rather than the non-generic &lt;strong&gt;ArrayList&lt;/strong&gt;.&lt;/p&gt;
&lt;div class="informalexample"&gt;
&lt;pre class="programlisting"&gt;
// Implement IComparable&amp;lt;T&amp;gt;.

using System;
using System.Collections.Generic;

// Implement the generic IComparable&amp;lt;T&amp;gt; interface.
class Inventory : IComparable&amp;lt;Inventory&amp;gt; {
  string name;
  double cost;
  int onhand;

  public Inventory(string n, double c, int h) {
    name = n;
    cost = c;
    onhand = h;
  }

  public override string ToString() {
    return
      String.Format("{0,-10}Cost: {1,6:C}  On hand: {2}",
                    name, cost, onhand);
  }

  // Implement the IComparable&amp;lt;T&amp;gt; interface.
  public int CompareTo(Inventory obj) {
    return name.CompareTo(obj.name);
  }

}

class GenericIComparableDemo {
  public static void Main() {
    List&amp;lt;Inventory&amp;gt; inv = new List&amp;lt;Inventory&amp;gt;();

    // Add elements to the list
    inv.Add(new Inventory("Pliers", 5.95, 3));
    inv.Add(new Inventory("Wrenches", 8.29, 2));
    inv.Add(new Inventory("Hammers", 3.50, 4));
    inv.Add(new Inventory("Drills", 19.88, 8));

    Console.WriteLine("Inventory list before sorting:");
    foreach(Inventory i in inv) {
      Console.WriteLine("   " + i);
    }
    Console.WriteLine();

    // Sort the list.
    inv.Sort();

    Console.WriteLine("Inventory list after sorting:");
    foreach(Inventory i in inv) {
      Console.WriteLine("   " + i);
    }
  }
}
&lt;/pre&gt;&lt;/div&gt;
&lt;p class="last-para"&gt;This program produces the same output as the previous, non-generic version.&lt;/p&gt;
&lt;/div&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/5240107523943415718/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/how-to-implement-icomparable-in-c.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5240107523943415718" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/5240107523943415718" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/how-to-implement-icomparable-in-c.html" rel="alternate" title="How to Implement IComparable in C#" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-979102946207364014.post-1560911755454134663</id><published>2008-10-16T11:56:00.001+05:30</published><updated>2008-10-16T11:56:29.632+05:30</updated><category scheme="http://www.blogger.com/atom/ns#" term="C# Collections"/><title type="text">C# Collections</title><content type="html">&lt;p class="first-para"&gt;The principal benefit of collections is that they standardize the way groups of objects are handled by your programs. All collections are designed around a set of clearly defined interfaces. Several built-in implementations of these interfaces, such as &lt;strong&gt;ArrayList&lt;/strong&gt;, &lt;strong&gt;Hashtable&lt;/strong&gt;, &lt;strong&gt;Stack&lt;/strong&gt;, and &lt;strong&gt;Queue&lt;/strong&gt;, are provided, which you can use as-is. You can also implement your own collection, but you will seldom need to.&lt;/p&gt;
&lt;p class="para"&gt;The .NET Framework supports four general types of collections: non-generic, specialized, bit based, and generic. The first three have been part of C# since version 1.0. The generic collections were added by C# 2.0. &lt;/p&gt;
&lt;p class="para"&gt;The non-generic collections implement several fundamental data structures, including a dynamic array, stack, and queue. They also include &lt;em&gt;dictionaries,&lt;/em&gt; in which you can store key/ value pairs. An essential point to understand about the non-generic collections is that they operate on data of type &lt;strong&gt;object&lt;/strong&gt;. Thus, they can be used to store any type of data, and different types of data can be mixed within the same collection. Of course, because they store &lt;strong&gt;object&lt;/strong&gt; references, they are not type-safe. The non-generic collection classes and interfaces are in &lt;strong&gt;System.Collections&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;The specialized collections operate on a specific type of data or operate in a unique way. For example, there are specialized collections for strings. There are also specialized collections that use a singly linked list. The specialized collections are declared in &lt;strong&gt;System.Collections&lt;/strong&gt;&lt;strong&gt;.Specialized&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;C# defines one bit-based collection called &lt;strong&gt;BitArray&lt;/strong&gt;. &lt;strong&gt;BitArray&lt;/strong&gt; supports bitwise operations on bits, such as AND and XOR. As such, it differs significantly in its capabilities from the other collections. &lt;strong&gt;BitArray&lt;/strong&gt; is declared in &lt;strong&gt;System.Collections&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;The generic collections provide generic implementations of several standard data structures, such as linked lists, stacks, queues, and dictionaries. Because these collections are generic, they are type-safe. This means that only items that are type-compatible with the type of the collection can be stored in a generic collection, thus eliminating accidental type mismatches. Generic collections were added by C# 2.0 and are declared in &lt;strong&gt;System.Collections&lt;/strong&gt;&lt;strong&gt;.Generic&lt;/strong&gt;.&lt;/p&gt;
&lt;p class="para"&gt;There are also three classes in the &lt;strong&gt;System.Collections.ObjectModel&lt;/strong&gt; namespace that support programmers who want to create their own generic collections.&lt;/p&gt;
&lt;p class="para"&gt;Fundamental to all collections is the concept of an &lt;em&gt;enumerator,&lt;/em&gt; which is supported by the &lt;strong&gt;IEnumerator&lt;/strong&gt; and &lt;strong&gt;IEnumerable&lt;/strong&gt; interfaces. An enumerator provides a standardized way of accessing the elements within a collection, one at a time. Thus, it &lt;em&gt;enumerates&lt;/em&gt; the contents of a collection. Because each collection must implement &lt;strong&gt;IEnumerable&lt;/strong&gt;, the elements of any collection class can be accessed through the methods defined by &lt;strong&gt;IEnumerator&lt;/strong&gt;. Therefore, with only small changes, the code that cycles through one type of collection can be used to cycle through another. As a point of interest, the &lt;strong&gt;foreach&lt;/strong&gt; loop uses the enumerator to cycle through the contents of a collection.&lt;/p&gt;
&lt;p class="para"&gt;A feature related to &lt;strong&gt;IEnumerator&lt;/strong&gt; and &lt;strong&gt;IEnumerable&lt;/strong&gt; is the &lt;em&gt;iterator.&lt;/em&gt; Iterators were added by C# 2.0. They simplify the process of creating classes, such as custom collections, that can be cycled through by a &lt;strong&gt;foreach&lt;/strong&gt; loop. Iterators are also described in this chapter.&lt;/p&gt;
&lt;p class="para"&gt;One last thing: If you are familiar with C++, then you will find it helpful to know that C# collection classes are similar in spirit to the Standard Template Library (STL) classes defined by C++. What C++ calls a container, C# calls a collection. The same is true of Java. If you are familiar with Java's Collections Framework, then you will have no trouble learning to use C# collections.&lt;/p&gt;
&lt;p class="last-para"&gt;Because of the differences between the four types of collections-non-generic, bit-based, specialized, and generic-this chapter discusses each separately.&lt;/p&gt;
&lt;p xmlns="" class="zoundry_raven_tags"&gt;
  &lt;!-- Tag links generated by Zoundry Raven. Do not manually edit. http://www.zoundryraven.com --&gt;
  &lt;span class="ztags"&gt;&lt;span class="ztagspace"&gt;Technorati&lt;/span&gt; : &lt;a href="http://www.technorati.com/tag/C%23+Collections" class="ztag" rel="tag"&gt;C# Collections&lt;/a&gt;&lt;/span&gt; 
&lt;/p&gt;</content><link href="http://csharp-slackers.blogspot.com/feeds/1560911755454134663/comments/default" rel="replies" title="Post Comments" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-collections.html#comment-form" rel="replies" title="0 Comments" type="text/html"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1560911755454134663" rel="edit" type="application/atom+xml"/><link href="http://www.blogger.com/feeds/979102946207364014/posts/default/1560911755454134663" rel="self" type="application/atom+xml"/><link href="http://csharp-slackers.blogspot.com/2008/10/c-collections.html" rel="alternate" title="C# Collections" type="text/html"/><author><name>vijay</name><uri>http://www.blogger.com/profile/03249092863649882869</uri><email>noreply@blogger.com</email><gd:image height="16" rel="http://schemas.google.com/g/2005#thumbnail" src="https://img1.blogblog.com/img/b16-rounded.gif" width="16"/></author><thr:total>0</thr:total></entry></feed>