<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3977111882153719926</id><updated>2024-09-01T08:08:58.407-07:00</updated><category term="Advanced .Net"/><category term="Quick Code Snaps"/><category term=".Net Question"/><category term="Delegate"/><category term="Delegate VS Interface"/><category term="Delegates VS Interfaces"/><category term="Dot Net Questions"/><category term="Interface"/><title type='text'>.Net</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-8379684991596654594</id><published>2014-12-20T03:24:00.000-08:00</published><updated>2014-12-20T03:42:30.695-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".Net Question"/><category scheme="http://www.blogger.com/atom/ns#" term="Dot Net Questions"/><title type='text'>Dot Net Questions - Part 1</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;
&lt;ol&gt;
&lt;li&gt;How you can build Robust, Scalable and Fault Tolerant&amp;nbsp;application?&lt;/li&gt;
&lt;li&gt;What is a smart Client?&lt;/li&gt;
&lt;li&gt;How to handle a situation where Service data contract is changing very frequently?&lt;/li&gt;
&lt;li&gt;How GC works.&lt;/li&gt;
&lt;li&gt;What if dispose function is not implemented then how you will release unmanaged resources?&lt;/li&gt;
&lt;li&gt;What if your application is loading lots of data at startup?&amp;nbsp;Your application will be unresponsive until all the data is not loaded. What are the different ways to handle this situation?&lt;/li&gt;
&lt;li&gt;What is Covariance and Contravariance&lt;/li&gt;
&lt;li&gt;IEnumerable vs IQueryable&lt;/li&gt;
&lt;li&gt;How finalize method will impact GC?&lt;/li&gt;
&lt;li&gt;SQL - Lets say there are millions of records in a table, provide the options to optimize its performance.&lt;/li&gt;
&lt;li&gt;SQL - What are the different ways to optimize&amp;nbsp;SQL server&#39;s performance?&lt;/li&gt;
&lt;/ol&gt;
&amp;nbsp;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/8379684991596654594/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2014/12/dot-net-interview-questions-part-1.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/8379684991596654594'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/8379684991596654594'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2014/12/dot-net-interview-questions-part-1.html' title='Dot Net Questions - Part 1'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-8489528616820541678</id><published>2013-08-24T10:50:00.001-07:00</published><updated>2013-08-24T11:31:12.928-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Quick Code Snaps"/><title type='text'>IXmlSerializable – Control XML Serialization</title><content type='html'>&lt;p&gt;Sometimes we are in hard need to control the xml serialization. One of these needs could be to reduce the serialized data, so that less data will travel over wire and hence we will get the improved data transfer speed. &lt;/p&gt; &lt;p&gt;To control it, we can use the &lt;font face=&quot;Consolas&quot;&gt;IXmlSerializable&lt;/font&gt; interface. This interface contains three functions &lt;/p&gt; &lt;ol&gt; &lt;li&gt;XmlSchema GetSchema() &lt;/li&gt; &lt;li&gt;void ReadXml(XmlReader reader) &lt;/li&gt; &lt;li&gt;void WriteXml(XmlWriter writer) &lt;/li&gt;&lt;/ol&gt; &lt;p&gt;In these functions, we can control the serialization with the help of &lt;font face=&quot;Consolas&quot;&gt;XMLReader&lt;/font&gt; and &lt;font face=&quot;Consolas&quot;&gt;XMLWriter&lt;/font&gt;. &lt;font face=&quot;Consolas&quot;&gt;IXmlSerializable&lt;/font&gt; interface is recognized by the both &lt;font face=&quot;Consolas&quot;&gt;XmlSerializer&lt;/font&gt; and Data Contract Serializer; and hence it can be used used by WCF and ASMX Web Services.&lt;/p&gt; &lt;p&gt;Lets have a look into the code -&amp;nbsp; &lt;/p&gt; &lt;h4&gt;Code&lt;/h4&gt;&lt;pre&gt;using System;&lt;br /&gt;using System.Xml;&lt;br /&gt;using System.Xml.Linq;&lt;br /&gt;using System.Xml.Schema;&lt;br /&gt;using System.Xml.Serialization;&lt;br /&gt;&lt;br /&gt;namespace XMLSerialization&lt;br /&gt;{&lt;br /&gt;    internal class Program&lt;br /&gt;    {&lt;br /&gt;        private static void Main(string[] args)&lt;br /&gt;        {&lt;br /&gt;            Person[] p = new Person[3];&lt;br /&gt;            p[0] = new Person() { Name = &quot;Sanjay&quot;, Age = 30 };&lt;br /&gt;            p[1] = new Person() { Name = &quot;Sanjay Legha&quot;, Age = 0 };&lt;br /&gt;            p[2] = new Person() { Age = 30 };&lt;br /&gt;&lt;br /&gt;            //Person p = new Person() { Name = &quot;Sanjay&quot;, Age = 50 };&lt;br /&gt;&lt;br /&gt;            string filePath = @&quot;D:\Sanjay\TempCode\XMLSerialization\XMLSerialization\bin\Debug\Serialized.xml&quot;;&lt;br /&gt;            using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))&lt;br /&gt;            {&lt;br /&gt;                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());&lt;br /&gt;                x.Serialize(fs, p);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open))&lt;br /&gt;            {&lt;br /&gt;                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());&lt;br /&gt;                object obj = x.Deserialize(fs);&lt;br /&gt;            }&lt;br /&gt;&lt;br /&gt;            Console.Write(&quot;Done&quot;);&lt;br /&gt;            Console.Read();&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public class Person : IXmlSerializable&lt;br /&gt;    {&lt;br /&gt;        public Person()&lt;br /&gt;        {&lt;br /&gt;            this.Name = string.Empty;&lt;br /&gt;            this.Age = 0;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [XmlElement(IsNullable = false)]&lt;br /&gt;        public string Name { get; set; }&lt;br /&gt;&lt;br /&gt;        [XmlElement()]&lt;br /&gt;        public int Age { get; set; }&lt;br /&gt;&lt;br /&gt;        public XmlSchema GetSchema()&lt;br /&gt;        {&lt;br /&gt;            return null;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void ReadXml(XmlReader reader)&lt;br /&gt;        {&lt;br /&gt;            if (reader.NodeType == XmlNodeType.Element)&lt;br /&gt;            {&lt;br /&gt;                XElement el = XNode.ReadFrom(reader) as XElement;&lt;br /&gt;&lt;br /&gt;                foreach (var item in el.Nodes())&lt;br /&gt;                {&lt;br /&gt;                    if (item is XElement)&lt;br /&gt;                    {&lt;br /&gt;                        XElement node = item as XElement;&lt;br /&gt;                        switch (node.Name.LocalName)&lt;br /&gt;                        {&lt;br /&gt;                            case &quot;Name&quot;:&lt;br /&gt;                                this.Name = node.Value;&lt;br /&gt;                                break;&lt;br /&gt;&lt;br /&gt;                            case &quot;Age&quot;:&lt;br /&gt;                                this.Age = Convert.ToInt32(node.Value);&lt;br /&gt;                                break;&lt;br /&gt;                        }&lt;br /&gt;                    }&lt;br /&gt;                }&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        public void WriteXml(XmlWriter writer)&lt;br /&gt;        {&lt;br /&gt;            if (!string.IsNullOrWhiteSpace(Name))&lt;br /&gt;                writer.WriteElementString(&quot;Name&quot;, Name);&lt;br /&gt;&lt;br /&gt;            if (Age != 0)&lt;br /&gt;                writer.WriteElementString(&quot;Age&quot;, Age.ToString());&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;h4&gt;Output&lt;/h4&gt;&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot;?&amp;gt;&lt;br&gt;&amp;lt;ArrayOfPerson xmlns:xsi=&quot;&lt;a href=&quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&quot;&gt;http://www.w3.org/2001/XMLSchema-instance&quot;&lt;/a&gt; xmlns:xsd=&quot;&lt;a href=&quot;http://www.w3.org/2001/XMLSchema&amp;quot;&quot;&gt;http://www.w3.org/2001/XMLSchema&quot;&lt;/a&gt;&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;Person&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Name&amp;gt;Sanjay&amp;lt;/Name&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Age&amp;gt;30&amp;lt;/Age&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;/Person&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;Person&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Name&amp;gt;Sanjay Legha&amp;lt;/Name&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;/Person&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;Person&amp;gt;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Age&amp;gt;30&amp;lt;/Age&amp;gt;&lt;br&gt;&amp;nbsp; &amp;lt;/Person&amp;gt;&lt;br&gt;&amp;lt;/ArrayOfPerson&amp;gt;&lt;br&gt;&lt;br&gt;&lt;/pre&gt;  </content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/8489528616820541678/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2013/08/ixmlserializable-control-xml.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/8489528616820541678'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/8489528616820541678'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2013/08/ixmlserializable-control-xml.html' title='IXmlSerializable – Control XML Serialization'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-2173889250253870253</id><published>2013-08-24T06:52:00.001-07:00</published><updated>2013-08-24T06:53:16.939-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Quick Code Snaps"/><title type='text'>Generic Serialize Deserialize - XmlSerializer</title><content type='html'>&lt;p&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;A generic Xml Serializer De-Serializer code snap&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;public class SerializeDeserialize&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static void SerializeData&amp;lt;T&amp;gt;(string filePath, T data)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew))&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(data.GetType());&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.Serialize(fs, data);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }  &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static T DeSerializeData&amp;lt;T&amp;gt;(string filePath)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; T data; &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; using (System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; object obj = x.Deserialize(fs);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; data = (T)obj;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }  &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return data;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/p&gt;&lt;/blockquote&gt;  </content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/2173889250253870253/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2013/08/generic-serialize-deserialize.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/2173889250253870253'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/2173889250253870253'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2013/08/generic-serialize-deserialize.html' title='Generic Serialize Deserialize - XmlSerializer'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-1362638323643653481</id><published>2012-02-25T05:46:00.001-08:00</published><updated>2012-04-22T02:37:13.790-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Advanced .Net"/><title type='text'>Programmatically Compile And Use Code Using C#</title><content type='html'>&lt;META NAME=&quot;description&quot; CONTENT=&quot;It is always better if you could create all your required classes in your project. But, sometimes it becomes very crucial if you could create a class for the specific situation at runtime or if you could change the existing one.&quot; /&gt;
&lt;META NAME=&quot;keywords&quot; CONTENT=&quot;Programmatically Compile Code Using C Sharp, Code Compile in C Sharp, Create DLL Runtime, Generate DLL Runtime and Consume, Dynamic Code Writing and Using in C Sharp&quot; /&gt;
&lt;META NAME=&quot;robot&quot; CONTENT=&quot;index,follow&quot; /&gt;
&lt;META NAME=&quot;author&quot; CONTENT=&quot;Sanjay Legha&quot; /&gt;
&lt;META NAME=&quot;revisit-after&quot; CONTENT=&quot;5&quot; /&gt;

&lt;h2&gt;&amp;nbsp;&lt;/h2&gt; &lt;h2&gt;Introduction&lt;/h2&gt; &lt;p&gt;It is always better if you could create all your required classes in your project. But, sometimes it becomes very crucial if you could create a class for the specific situation at runtime or if you could change the existing one.&lt;/p&gt; &lt;p&gt;To overcome this situation, .Net Framework exposes some class that allow us to programmatically access the C# language compiler.&lt;/p&gt; &lt;p&gt;In this post I am demonstrating how to create an &lt;strong&gt;entity &lt;/strong&gt;class and its &lt;strong&gt;collection &lt;/strong&gt;class through a windows application, and passing the collection class object to the DataGridView as DataSource.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Note: &lt;/strong&gt;I am assuming you have the basic knowledge of reflection.&lt;/p&gt; &lt;h2&gt;How To&lt;/h2&gt; &lt;p&gt;&lt;strong&gt;Setup the project and form&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;In this example I am using the basic windows forms application. You can follow the following steps to setup this application - &lt;/p&gt; &lt;ul&gt; &lt;li&gt;Create a &lt;font face=&quot;Lucida Console&quot;&gt;Windows Forms Application&lt;/font&gt;. It will create a form with name &lt;font face=&quot;Lucida Console&quot;&gt;Form1&lt;/font&gt;.  &lt;li&gt;Add a button on &lt;font face=&quot;Lucida Console&quot;&gt;Form1&lt;/font&gt; and name it &lt;font face=&quot;Lucida Console&quot;&gt;btnCompile&lt;/font&gt;.  &lt;li&gt;Add a &lt;font face=&quot;Lucida Console&quot;&gt;DataGridView&lt;/font&gt;. Here I am using its default name &lt;font face=&quot;Lucida Console&quot;&gt;dataGridView1&lt;/font&gt;.  &lt;li&gt;Double click on the &lt;font face=&quot;Lucida Console&quot;&gt;btnCompile&lt;/font&gt; to generate the event handler.&lt;/li&gt;&lt;/ul&gt; &lt;h2&gt;&amp;nbsp;&lt;/h2&gt; &lt;p&gt;&lt;strong&gt;Implement the compiler&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;After adding code in event handler, your code should look like -&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;private void btnCompile_Click(object sender, EventArgs e)&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // code string to compile&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; string code =&lt;br&gt;@&quot;class EntityCollection : System.Collections.Generic.List&amp;lt;Entity&amp;gt; {}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;class Entity&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public string Name { get; set; }&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public int Age { get; set; }&lt;br&gt;}&quot;;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // RETRIEVING COMPILER INTERFACE&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; CSharpCodeProvider codeProvider = new CSharpCodeProvider();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ICodeCompiler codeCompiler = codeProvider.CreateCompiler();&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;br&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // PREPARING COMPILER PARAMETERS&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; CompilerParameters compilerParameters = new CompilerParameters();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; compilerParameters.GenerateInMemory = true;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; compilerParameters.TreatWarningsAsErrors = false;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; compilerParameters.WarningLevel = 4;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; compilerParameters.ReferencedAssemblies.Add(&quot;System.dll&quot;);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // COMPILING CODE&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; CompilerResults results = codeCompiler.CompileAssemblyFromSource(compilerParameters, code);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (results.Errors.Count &amp;gt; 0)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; StringBuilder sbExceptions = new StringBuilder();&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (CompilerError CompErr in results.Errors)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sbExceptions.AppendLine(&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;Line number &quot; + CompErr.Line +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;, Error Number: &quot; + CompErr.ErrorNumber +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;, &#39;&quot; + CompErr.ErrorText + &quot;;&quot; +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Environment.NewLine + Environment.NewLine);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MessageBox.Show(&quot;Exception raised while compiling your code: \n\n&quot; + sbExceptions.ToString());&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // GETTING COMPILED ASSEMBLY&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Assembly assembly = results.CompiledAssembly;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // RETRIEVING COLLECTION CLASS FROM COMPILED ASSEMBLY. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type type = assembly.GetType(&quot;EntityCollection&quot;);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // CREATING INSTANCE OF COLLECTION CLASS&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IList list = (IList)Activator.CreateInstance(type);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // RETRIEVING ENTITY CLASS FROM COMPILED ASSEMBLY. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type eType = assembly.GetType(&quot;Entity&quot;);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; object obj = Activator.CreateInstance(eType);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ASSIGNING VALUES TO THE ENTITY CLASS OBJECT. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eType.GetProperty(&quot;Name&quot;).SetValue(obj, &quot;Sanjay&quot;, null);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eType.GetProperty(&quot;Age&quot;).SetValue(obj, 30, null);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ADDING CLASS TO COLLECTION OBJECT&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; list.Add(obj);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ASSIGNED LIST TO GRID VIEW AS DATA SOURCE&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataGridView1.DataSource = list;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;strong&gt;About code&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;.NET Framework provides the &lt;font face=&quot;Lucida Console&quot;&gt;ICodeCompiler&lt;/font&gt; compiler execution interface.The &lt;font face=&quot;Lucida Console&quot;&gt;CSharpCodeProvider &lt;/font&gt;class implements this interface and provides access to the C# code compiler. The following code creates an instance of &lt;font face=&quot;Lucida Console&quot;&gt;CSharpCodeProvider &lt;/font&gt;and initializes &lt;font face=&quot;Lucida Console&quot;&gt;ICodeCompiler&lt;/font&gt; interface object.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;CSharpCodeProvider codeProvider = new CSharpCodeProvider();&lt;br&gt;ICodeCompiler codeCompiler = codeProvider.CreateCompiler();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Now you have the compiler interface which can be used to compile your source code. You need to pass parameters to the compiler by using the &lt;font face=&quot;Lucida Console&quot;&gt;CompilerParameters&lt;/font&gt; class.&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;CompilerParameters compilerParameters = new CompilerParameters();&lt;br&gt;compilerParameters.GenerateInMemory = true;&lt;br&gt;compilerParameters.TreatWarningsAsErrors = false;&lt;br&gt;compilerParameters.WarningLevel = 4;&lt;br&gt;compilerParameters.ReferencedAssemblies.Add(&quot;System.dll&quot;);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;CompilerResults results = codeCompiler.CompileAssemblyFromSource(compilerParameters, code);&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;font face=&quot;Lucida Console&quot;&gt;CompilerParameters&lt;/font&gt; object is used to pass parameters to tell the compiler that you want to generate a class library in memory which can be used further in the code. To compile code you will use function &lt;font face=&quot;Lucida Console&quot;&gt;CompileAssemblyFromSource&lt;/font&gt;. &lt;font face=&quot;Lucida Console&quot;&gt;CompileAssemblyFromSource&lt;/font&gt; method takes the &lt;font face=&quot;Lucida Console&quot;&gt;compilerParameters&lt;/font&gt; object and the source code, which is a string. &lt;/p&gt; &lt;p&gt;Once the code is compiled, you can check to see if there were any compilation errors. You can use the return value from &lt;font face=&quot;Lucida Console&quot;&gt;CompileAssemblyFromSource&lt;/font&gt; method, which is a &lt;font face=&quot;Lucida Console&quot;&gt;CompilerResults&lt;/font&gt; object. This object contains an errors collection, which contains any errors that occurred during the compilation process.&lt;/p&gt; &lt;p&gt;Below code collects all the errors in the string builder class which is for demonstration only which you can user for your purpose - &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;if (results.Errors.Count &amp;gt; 0)&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; StringBuilder sbExceptions = new StringBuilder();&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (CompilerError CompErr in results.Errors)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sbExceptions.AppendLine(&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;Line number &quot; + CompErr.Line +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;, Error Number: &quot; + CompErr.ErrorNumber +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &quot;, &#39;&quot; + CompErr.ErrorText + &quot;;&quot; +&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Environment.NewLine + Environment.NewLine);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; MessageBox.Show(&quot;Exception raised while compiling your code: \n\n&quot; + sbExceptions.ToString());&lt;br&gt;}&lt;/font&gt;&lt;br&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Once the assembly is generated without any error you can use it in your code. I have used it to generate a list of items and binded this list to the grid view as its data source - &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;else&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // GETTING COMPILED ASSEMBLY&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Assembly assembly = results.CompiledAssembly;&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // RETRIEVING COLLECTION CLASS FROM COMPILED ASSEMBLY. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type type = assembly.GetType(&quot;EntityCollection&quot;);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // CREATING INSTANCE OF COLLECTION CLASS&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IList list = (IList)Activator.CreateInstance(type);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // RETRIEVING ENTITY CLASS FROM COMPILED ASSEMBLY. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Type eType = assembly.GetType(&quot;Entity&quot;);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; object obj = Activator.CreateInstance(eType);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ASSIGNING VALUES TO THE ENTITY CLASS OBJECT. &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eType.GetProperty(&quot;Name&quot;).SetValue(obj, &quot;Sanjay&quot;, null);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eType.GetProperty(&quot;Age&quot;).SetValue(obj, 30, null);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ADDING CLASS TO COLLECTION OBJECT&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; list.Add(obj);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // ASSIGNED LIST TO GRID VIEW AS DATA SOURCE&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataGridView1.DataSource = list;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;&lt;br&gt;&lt;/p&gt; &lt;p&gt;Once the compilation successes, build assembly can be retrieved from &lt;font face=&quot;Lucida Console&quot;&gt;CompileAssemblyFromSource&lt;/font&gt; method’s return value which contains &lt;font face=&quot;Lucida Console&quot;&gt;CompiledAssembly&lt;/font&gt; property.&lt;/p&gt; &lt;p&gt;Now you have the compiled assembly. You can play with it as you wish. &lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/1362638323643653481/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/how-to-programmatically-compile-and-use.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/1362638323643653481'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/1362638323643653481'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/how-to-programmatically-compile-and-use.html' title='Programmatically Compile And Use Code Using C#'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-1367316003997157325</id><published>2012-02-12T07:15:00.001-08:00</published><updated>2012-03-21T23:57:40.119-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Advanced .Net"/><title type='text'>Extension Methods In Dot Net, C#</title><content type='html'>&lt;p align=&quot;justify&quot;&gt;Sometimes we are in need to extend any class but often it is just not possible to use inheritance if you are working with a value type, a sealed class, or an interface. C# 3 introduces the idea of extension methods.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Extension methods allows an existing type to be extended with new methods without altering the definition of the original type. &lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;SYNTAX&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;You cannot use any method as the extension method – it has to have the following characteristics:&lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;It has to be in a non-nested, non-generic static class and therefore has to be a static method.&lt;/div&gt;&lt;/li&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;It has to have at least one parameter where the type of the first parameter will be the type that is extends.&lt;/div&gt;&lt;/li&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;The first parameter has to be prefixed with &lt;font face=&quot;Lucida Console&quot;&gt;this&lt;/font&gt; keyword.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p align=&quot;justify&quot;&gt;In final words, an extension method is a static method of a static class, where the &lt;font face=&quot;Lucida Console&quot;&gt;this &lt;/font&gt;modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. &lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;For example:&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;namespace ExtensionMethods&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static class MyExtensions&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static int WordCount(this String str)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return str.Split(new char[] { &#39; &#39;, &#39;.&#39;, &#39;?&#39; }, &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; StringSplitOptions.RemoveEmptyEntries).Length;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&amp;nbsp;&amp;nbsp; &lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Syntax Explanation&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;MyExtensions&lt;/font&gt; class is a static class and &lt;font face=&quot;Lucida Console&quot;&gt;WordCount&lt;/font&gt; is a static method of static class. &lt;font face=&quot;Lucida Console&quot;&gt;this&lt;/font&gt; keyword tells that this is an extension method. Type of first parameter tells it is extending &lt;font face=&quot;Lucida Console&quot;&gt;string &lt;/font&gt;class. &lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Usage&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;The &lt;font face=&quot;Lucida Console&quot;&gt;WordCounts&lt;/font&gt; extension method can be called as it was an instance method of a string class, as follows:&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;Console.WriteLine (&quot;Hello Extension Methods&quot;.WordCount());&lt;/font&gt;&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;or&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;string s = &quot;Hello Extension Methods&quot;;&lt;br&gt;int i = s.WordCount();&lt;/font&gt;&lt;br&gt;&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;strong&gt;Note: &lt;/strong&gt;Extension methods are only in scope when you explicitly import the namespace into your source code with a &lt;font face=&quot;Lucida Console&quot;&gt;using&lt;/font&gt; directive.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler &lt;em&gt;translates your code into a call on the static method&lt;/em&gt;. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The above function’s translation will be as follows:&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;Console.WriteLine (MyExtensions.WordCount(&quot;Hello Extension Methods&quot;));&lt;/font&gt;&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Extending Interfaces&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;LINQ has already extended lots of interfaces like, &lt;font face=&quot;Lucida Console&quot;&gt;IEnumerable, IEnumerable&amp;lt;T&amp;gt;, IList, IList&amp;lt;T&amp;gt;&lt;/font&gt; etc.&lt;/p&gt; &lt;p&gt;A simple syntax of how to extend the interface is:&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;public static T First&amp;lt;T&amp;gt; (this IEnumerable&amp;lt;T&amp;gt; sequence)&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foreach (T element in sequence)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return element;&lt;/font&gt;&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; throw new InvalidOperationException (&quot;No elements found!&quot;);&lt;br&gt;}&lt;br&gt;...&lt;br&gt;Console.WriteLine ((new int[]{23,453,345}).First());&lt;/font&gt;&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Extension Method Chaining&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;Extension methods, like instance methods, provide a tidy way to chain functions. Consider the following two functions:&lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;IList&amp;lt;string&amp;gt; strings = new List&amp;lt;string&amp;gt;();&lt;br&gt;strings.Add(&quot;Hello&quot;);&lt;br&gt;strings.Add(&quot;Extension&quot;);&lt;br&gt;strings.Add(&quot;Methods&quot;);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;strings.First().WordCount();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Ambiguity and Resolution&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;As mentioned above, Extension Methods are only in scope when you explicitly import the namespace into your source code with a &lt;font face=&quot;Lucida Console&quot;&gt;using&lt;/font&gt; directive. Consider the extension method &lt;font face=&quot;Lucida Console&quot;&gt;WordCount,&lt;/font&gt; the following application must import &lt;font face=&quot;Lucida Console&quot;&gt;ExtensionMethods&lt;/font&gt;, in order to avoid a compile-time error:&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;namespace TestApp&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; using ExtensionMethods; // importing namespace &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class Test&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main()&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine (&quot;Hello Extension Methods&quot;.WordCount());&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Extension methods v.s. instance methods&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;As per the standard preference rule, any compatible instance method will always take precedence over the extension method. In the following example, &lt;font face=&quot;Lucida Console&quot;&gt;Test&lt;/font&gt;’s &lt;font face=&quot;Lucida Console&quot;&gt;Foo&lt;/font&gt; method will always take precedence even when called with an argument &lt;font face=&quot;Lucida Console&quot;&gt;x&lt;/font&gt; of type &lt;font face=&quot;Lucida Console&quot;&gt;int&lt;/font&gt;:&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;class Test&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Foo (object x) { } // This method always wins&lt;br&gt;}&lt;br&gt;static class Extensions&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static void Foo (this Test t, int x) { }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p align=&quot;justify&quot;&gt;The only way to call the extension method in this case is via normal static syntax-&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;Extensions.Foo(...).&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;h2 align=&quot;justify&quot;&gt;&lt;font size=&quot;2&quot;&gt;Extension methods versus extension methods&lt;/font&gt;&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;If two extension methods have the same signature then the method must be called as an ordinary static method to resolve ambiguity. &lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;If one extension method has more specific arguments, then the more specific method takes precedence. To illustrate, consider the following two classes:&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;static class StringExtensions&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static int WordCount (this string s) {...}&lt;br&gt;}&lt;br&gt;static class ObjectExtensions&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static int WordCount (this object s) {...}&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p align=&quot;justify&quot;&gt;The following code calls &lt;font face=&quot;Lucida Console&quot;&gt;StringExtensions&lt;/font&gt;’s &lt;font face=&quot;Lucida Console&quot;&gt;WordCount&lt;/font&gt; method:&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;int wordCount = &quot;Hello Extension Methods&quot;.WordCount();&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p align=&quot;justify&quot;&gt;To call &lt;font face=&quot;Lucida Console&quot;&gt;ObjectExtensions&lt;/font&gt;’s &lt;font face=&quot;Lucida Console&quot;&gt;WordCount&lt;/font&gt; method, we must specify it explicitly:&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;int wordCount = (ObjectExtensions.WordCount (&quot;Hello Extension Methods&quot;));&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/1367316003997157325/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/extension-methods.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/1367316003997157325'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/1367316003997157325'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/extension-methods.html' title='Extension Methods In Dot Net, C#'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-9052089103409822085</id><published>2012-02-12T00:40:00.001-08:00</published><updated>2012-05-04T21:01:43.304-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Delegate"/><category scheme="http://www.blogger.com/atom/ns#" term="Delegate VS Interface"/><category scheme="http://www.blogger.com/atom/ns#" term="Delegates VS Interfaces"/><category scheme="http://www.blogger.com/atom/ns#" term="Interface"/><title type='text'>Delegates VS Interfaces</title><content type='html'>&lt;p align=&quot;justify&quot;&gt;Delegates and interfaces are similar in that they enable the separation of specification and implementation. Multiple independent authors can produce implementations that are compatible with an interface specification. Similarly, a delegate specifies the signature of a method, and authors can write methods that are compatible with the delegate specification. When should you use interfaces, and when should you use delegates?&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Delegates are useful when:&lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;A single method is being called.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;A class may want to have multiple implementations of the method specification.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;It is desirable to allow using a static method to implement the specification.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;An event-like design pattern is desired (for more information, see the &lt;a href=&quot;/2012/02/introduction-to-c-events.html&quot;&gt;Introduction To Events&lt;/a&gt; post).&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;The caller has no need to know or obtain the object that the method is defined on.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;The provider of the implementation wants to &quot;hand out&quot; the implementation of the&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;specification to only a few select components.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;Easy composition is desired.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p align=&quot;justify&quot;&gt;Interfaces are useful when: &lt;/p&gt; &lt;ul&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;The specification defines a set of related methods that will be called.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;A class typically implements the specification only once.&lt;/div&gt; &lt;li&gt; &lt;div align=&quot;justify&quot;&gt;The caller of the interface wants to cast to or from the interface type to obtain other interfaces or classes.&lt;br&gt;&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/9052089103409822085/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/delegates-vs-interfaces.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/9052089103409822085'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/9052089103409822085'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/delegates-vs-interfaces.html' title='Delegates VS Interfaces'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-5815766097882699838</id><published>2012-02-11T23:43:00.001-08:00</published><updated>2012-02-11T23:57:14.956-08:00</updated><title type='text'>Introduction to C# Events</title><content type='html'>&lt;p align=&quot;justify&quot;&gt;An &lt;strong&gt;&lt;em&gt;event &lt;/em&gt;&lt;/strong&gt;is a member that enables an object or class to provide notifications. Clients can attach executable code for events by supplying event handlers. Events work on &lt;font face=&quot;Lucida Console&quot;&gt;broadcaster / subscriber&lt;/font&gt; model where one object is &lt;strong&gt;&lt;em&gt;broadcasting&lt;/em&gt; &lt;/strong&gt;events and other attached objects are &lt;strong&gt;&lt;em&gt;subscribing&lt;/em&gt; &lt;/strong&gt;with those events.&lt;/p&gt; &lt;p&gt;Events are declared using &lt;em&gt;event-declarations&lt;/em&gt;:&lt;/p&gt; &lt;p&gt;&lt;em&gt;event-declaration:&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; event-modifier&lt;/em&gt; &lt;font face=&quot;Lucida Console&quot;&gt;event&lt;/font&gt;&amp;nbsp;&lt;em&gt;type&lt;/em&gt;&amp;nbsp;&lt;em&gt;variable-declaration&lt;/em&gt;;&lt;br&gt;&lt;br&gt;event-modifiers:&lt;br&gt;&lt;font face=&quot;Lucida Console&quot;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; new&lt;br&gt;&lt;font face=&quot;Lucida Console&quot;&gt;&lt;/font&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; internal&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; virtual&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sealed&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; override&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; abstract&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; extern&lt;/font&gt;&lt;/p&gt; &lt;p&gt;An &lt;em&gt;event-declaration &lt;/em&gt;may include a set of attributes and access modifiers, the &lt;font face=&quot;Lucida Console&quot;&gt;new, static, virtual, override, sealed, abstract&lt;/font&gt;, and &lt;font face=&quot;Lucida Console&quot;&gt;extern&lt;/font&gt; modifiers.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Event declarations are subject to the same rules as method declarations with regard to valid combinations of modifiers.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The &lt;em&gt;type &lt;/em&gt;of an event declaration must be a &lt;em&gt;delegate-type&lt;/em&gt;, and that &lt;em&gt;delegate-type&lt;/em&gt; must be at least as accessible as the event itself.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An event declaration may include &lt;em&gt;event-accessor-declarations&lt;/em&gt;. However, if it does not, for non-extern, non-abstract events, the compiler supplies them automatically; for extern events, the accessors are provided externally.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An event declaration that omits &lt;em&gt;event-accessor-declarations &lt;/em&gt;defines one or more events—one for each of the &lt;em&gt;variable-declarators&lt;/em&gt;. The attributes and modifiers apply to all of the members declared by such an &lt;em&gt;event-declaration&lt;/em&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;It is a compile-time error for an &lt;em&gt;event-declaration &lt;/em&gt;to include both the &lt;font face=&quot;Lucida Console&quot;&gt;abstract &lt;/font&gt;modifier and brace-delimited &lt;em&gt;event-accessor-declarations&lt;/em&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;When an event declaration includes an &lt;font face=&quot;Lucida Console&quot;&gt;extern &lt;/font&gt;modifier, the event is said to be an &lt;strong&gt;&lt;em&gt;external event&lt;/em&gt;&lt;/strong&gt;. Because an external event declaration provides no actual implementation, it is an error for it to include both the &lt;font face=&quot;Lucida Console&quot;&gt;extern &lt;/font&gt;modifier and &lt;em&gt;event-accessor-declarations&lt;/em&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An event can be used as the left-hand operand of the += and -= operators. These operators are used, respectively, to attach event handlers to or to remove event handlers from an event, and the access modifiers of the event control the contexts in which such operations are permitted.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Since += and -= are the only operations that are permitted on an event outside the type that declares the event, external code can add and remove handlers for an event, but cannot in any other way obtain or modify the underlying list of event handlers.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;In an operation of the form x += y or x -= y, when x is an event and the reference takes place outside the type that contains the declaration of x, the result of the operation has type &lt;font face=&quot;Lucida Console&quot;&gt;void &lt;/font&gt;(as opposed to having the type of x, with the value of x after the assignment). This rule prohibits external code from indirectly examining the underlying delegate of an event.&lt;/p&gt; &lt;p&gt;The following example shows how event handlers are attached to instances of the Button class:&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;public delegate void EventHandler(object sender, EventArgs e);&lt;br&gt;public class Button: Control&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event EventHandler Click;&lt;br&gt;}&lt;br&gt;public class LoginDialog: Form&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Button OkButton;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; Button CancelButton;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public LoginDialog() &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;font face=&quot;Courier New&quot;&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OkButton = new Button(...);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; OkButton.Click += new EventHandler(OkButtonClick);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; CancelButton = new Button(...);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; CancelButton.Click += new EventHandler(CancelButtonClick);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; void OkButtonClick(object sender, EventArgs e) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/font&gt;&lt;font face=&quot;Courier New&quot;&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Handle OkButton.Click event&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; void CancelButtonClick(object sender, EventArgs e) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Handle CancelButton.Click event&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Here, the &lt;font face=&quot;Lucida Console&quot;&gt;LoginDialog&lt;/font&gt; instance constructor creates two Button instances and attaches event handlers to the Click events.&lt;/p&gt; &lt;h2&gt;Field-like events&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;Within the program text of the class or struct that contains the declaration of an event, certain events can be used like fields. To be used in this way, an event must not be &lt;font face=&quot;Lucida Console&quot;&gt;abstract &lt;/font&gt;or &lt;font face=&quot;Lucida Console&quot;&gt;extern&lt;/font&gt;, and must not explicitly include &lt;em&gt;event-accessor-declarations&lt;/em&gt;. Such an event can be used in any context that permits a field. The field contains a delegate which refers to the list of event handlers that have been added to the event. If no event handlers have been added, the field contains &lt;font face=&quot;Lucida Console&quot;&gt;null&lt;/font&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;In the example&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;public delegate void EventHandler(object sender, EventArgs e);&lt;br&gt;public class Button: Control&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event EventHandler Click;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected void OnClick(EventArgs e) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (Click != null) Click(this, e);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public void Reset() &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Click = null;&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;Click&lt;/font&gt; is used as a field within the &lt;font face=&quot;Lucida Console&quot;&gt;Button &lt;/font&gt;class. As the example demonstrates, the field can be examined, modified, and used in delegate invocation expressions. The &lt;font face=&quot;Lucida Console&quot;&gt;OnClick &lt;/font&gt;method in the &lt;font face=&quot;Lucida Console&quot;&gt;Button &lt;/font&gt;class “raises” the &lt;font face=&quot;Lucida Console&quot;&gt;Click &lt;/font&gt;event. The notion of raising an event is precisely equivalent to invoking the delegate represented by the event—thus, there are no special language constructs for raising events. Note that the delegate invocation is preceded by a check that ensures the delegate is non-null.&lt;/p&gt; &lt;p&gt;Outside the declaration of the &lt;font face=&quot;Lucida Console&quot;&gt;Button &lt;/font&gt;class, the &lt;font face=&quot;Lucida Console&quot;&gt;Click &lt;/font&gt;member can only be used on the left-hand side of the += and –= operators, as in&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;b.Click += new EventHandler(…);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;which appends a delegate to the invocation list of the &lt;font face=&quot;Lucida Console&quot;&gt;Click &lt;/font&gt;event, and&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;b.Click –= new EventHandler(…);&lt;/font&gt;&lt;/p&gt; &lt;p&gt;which removes a delegate from the invocation list of the &lt;font face=&quot;Lucida Console&quot;&gt;Click&lt;/font&gt; event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;When compiling a field-like event, the compiler automatically creates storage to hold the delegate, and creates accessors for the event that add or remove event handlers to the delegate field. In order to be thread-safe, the addition or removal operations are done while holding the lock on the containing object for an instance event, or the type object for a static event.&lt;/p&gt; &lt;p&gt;Thus, an instance event declaration of the form:&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;class X&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event D Ev;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;could be compiled to something equivalent to: &lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;class X&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private D __Ev;&amp;nbsp; // field to hold the delegate&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event D Ev {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; add {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; lock(this) { __Ev = __Ev + value; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; remove {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; lock(this) { __Ev = __Ev - value; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;Within the class X, references to Ev are compiled to reference the hidden field __Ev instead. The name “__Ev” is arbitrary; the hidden field could have any name or no name at all.&lt;/p&gt; &lt;p&gt;Similarly, a static event declaration of the form:&lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;class X&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static event D Ev;&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;p&gt;could be compiled to something equivalent to: &lt;/p&gt; &lt;p&gt;&lt;font face=&quot;Courier New&quot;&gt;class X&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; private static D __Ev;&amp;nbsp; // field to hold the delegate&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static event D Ev {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; add {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; lock(typeof(X)) { __Ev = __Ev + value; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; remove {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; lock(typeof(X)) { __Ev = __Ev - value; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt; &lt;h2&gt;Event accessors&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;Event declarations typically omit &lt;em&gt;event-accessor-declarations&lt;/em&gt;, as in the Button example above. One situation for doing so involves the case in which the storage cost of one field per event is not acceptable. In such cases, a class can include &lt;em&gt;event-accessor-declarations&lt;/em&gt; and use a private mechanism for storing the list of event handlers.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The &lt;em&gt;event-accessor-declarations&lt;/em&gt; of an event specify the executable statements associated with adding and removing event handlers.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The accessor declarations consist of an &lt;em&gt;add-accessor-declaration&lt;/em&gt; and a &lt;em&gt;remove-accessor-declaration&lt;/em&gt;. Each accessor declaration consists of the token &lt;font face=&quot;Lucida Console&quot;&gt;add&lt;/font&gt; or &lt;font face=&quot;Lucida Console&quot;&gt;remove&lt;/font&gt; followed by a &lt;em&gt;block&lt;/em&gt;. The &lt;em&gt;block &lt;/em&gt;associated with an &lt;em&gt;add-accessor-declaration&lt;/em&gt; specifies the statements to execute when an event handler is added, and the &lt;em&gt;block &lt;/em&gt;associated with a &lt;em&gt;remove-accessor-declaration &lt;/em&gt;specifies the statements to execute when an event handler is removed.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Each &lt;em&gt;add-accessor-declaration &lt;/em&gt;and &lt;em&gt;remove-accessor-declaration &lt;/em&gt;corresponds to a method with a single value parameter of the event type and a &lt;font face=&quot;Lucida Console&quot;&gt;void&lt;/font&gt; return type. The implicit parameter of an event accessor is named &lt;font face=&quot;Lucida Console&quot;&gt;value&lt;/font&gt;. When an event is used in an event assignment, the appropriate event accessor is used. Specifically, if the assignment operator is += then the add accessor is used, and if the assignment operator is -= then the remove accessor is used. In either case, the right-hand operand of the assignment operator is used as the argument to the event accessor. The block of an &lt;em&gt;add-accessor-declaration&lt;/em&gt; or a &lt;em&gt;remove-accessor-declaration&lt;/em&gt; must conform to the rules for void methods. In particular, return statements in such a block are not permitted to specify an expression.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Since an event accessor implicitly has a parameter named &lt;font face=&quot;Lucida Console&quot;&gt;value&lt;/font&gt;, it is a compile-time error for a local variable or constant declared in an event accessor to have that name.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;In the example&lt;/p&gt; &lt;blockquote&gt; &lt;p align=&quot;justify&quot;&gt;&lt;font face=&quot;Courier New&quot;&gt;class Control: Component&lt;br&gt;{&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Unique keys for events&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static readonly object mouseDownEventKey = new object();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; static readonly object mouseUpEventKey = new object();&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Return event handler associated with key&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected Delegate GetEventHandler(object key) {...}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Add event handler associated with key&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected void AddEventHandler(object key, Delegate handler) {...}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Remove event handler associated with key&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected void RemoveEventHandler(object key, Delegate handler) {...}&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // MouseDown event&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event MouseEventHandler MouseDown {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; add { AddEventHandler(mouseDownEventKey, value); }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; remove { RemoveEventHandler(mouseDownEventKey, value); }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // MouseUp event&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; public event MouseEventHandler MouseUp {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; add { AddEventHandler(mouseUpEventKey, value); }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; remove { RemoveEventHandler(mouseUpEventKey, value); }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; // Invoke the MouseUp event&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; protected void OnMouseUp(MouseEventArgs args) {&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MouseEventHandler handler; &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; handler = (MouseEventHandler)GetEventHandler(mouseUpEventKey);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; if (handler != null)&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; handler(this, args);&lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br&gt;}&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p align=&quot;justify&quot;&gt;the &lt;font face=&quot;Lucida Console&quot;&gt;Control &lt;/font&gt;class implements an internal storage mechanism for events. The &lt;font face=&quot;Lucida Console&quot;&gt;AddEventHandler &lt;/font&gt;method associates a delegate value with a key, the &lt;font face=&quot;Lucida Console&quot;&gt;GetEventHandler &lt;/font&gt;method returns the delegate currently associated with a key, and the &lt;font face=&quot;Lucida Console&quot;&gt;RemoveEventHandler&lt;/font&gt; method removes a delegate as an event handler for the specified event. Presumably, the underlying storage mechanism is designed such that there is no cost for associating a &lt;font face=&quot;Lucida Console&quot;&gt;null&lt;/font&gt; delegate value with a key, and thus unhandled events consume no storage.&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;Static and instance events&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;When an event declaration includes a &lt;font face=&quot;Lucida Console&quot;&gt;static &lt;/font&gt;modifier, the event is said to be a &lt;strong&gt;&lt;em&gt;static event&lt;/em&gt;&lt;/strong&gt;. When no static modifier is present, the event is said to be an &lt;strong&gt;&lt;em&gt;instance event&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;A static event is not associated with a specific instance, and it is a compile-time error to refer to &lt;font face=&quot;Lucida Console&quot;&gt;this&lt;/font&gt; in the accessors of a static event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An instance event is associated with a given instance of a class, and this instance can be accessed as &lt;font face=&quot;Lucida Console&quot;&gt;this &lt;/font&gt;in the accessors of that event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;When an event is referenced in a &lt;em&gt;member-access&lt;/em&gt; of the form &lt;font face=&quot;Lucida Console&quot;&gt;E.M&lt;/font&gt;, if &lt;font face=&quot;Lucida Console&quot;&gt;M&lt;/font&gt; is a static event, &lt;font face=&quot;Lucida Console&quot;&gt;E&lt;/font&gt; must denote a type containing &lt;font face=&quot;Lucida Console&quot;&gt;M&lt;/font&gt;, and if &lt;font face=&quot;Lucida Console&quot;&gt;M&lt;/font&gt; is an instance event, &lt;font face=&quot;Lucida Console&quot;&gt;E&lt;/font&gt; must denote an instance of a type containing &lt;font face=&quot;Lucida Console&quot;&gt;M&lt;/font&gt;.&lt;/p&gt; &lt;h2 align=&quot;justify&quot;&gt;Virtual, sealed, override, and abstract accessors&lt;/h2&gt; &lt;p align=&quot;justify&quot;&gt;A &lt;font face=&quot;Lucida Console&quot;&gt;virtual&lt;/font&gt; event declaration specifies that the accessors of that event are virtual. The &lt;font face=&quot;Lucida Console&quot;&gt;virtual &lt;/font&gt;modifier applies to both accessors of an event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An &lt;font face=&quot;Lucida Console&quot;&gt;abstract &lt;/font&gt;event declaration specifies that the accessors of the event are virtual, but does not provide an actual implementation of the accessors. Instead, non-abstract derived classes are required to provide their own implementation for the accessors by overriding the event. Because an abstract event declaration provides no actual implementation, it cannot provide brace-delimited &lt;em&gt;event-accessor-declarations&lt;/em&gt;.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An event declaration that includes both the &lt;font face=&quot;Lucida Console&quot;&gt;abstract &lt;/font&gt;and &lt;font face=&quot;Lucida Console&quot;&gt;override &lt;/font&gt;modifiers specifies that the event is abstract and overrides a base event. The accessors of such an event are also abstract.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Abstract event declarations are only permitted in abstract classes.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The accessors of an inherited virtual event can be overridden in a derived class by including an event declaration that specifies an &lt;font face=&quot;Lucida Console&quot;&gt;override &lt;/font&gt;modifier. This is known as an &lt;em&gt;&lt;strong&gt;overriding event declaration&lt;/strong&gt;&lt;/em&gt;. An overriding event declaration does not declare a new event. Instead, it simply specializes the implementations of the accessors of an existing virtual event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An overriding event declaration must specify the exact same accessibility modifiers, type, and name as the overridden event.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An overriding event declaration may include the &lt;font face=&quot;Lucida Console&quot;&gt;sealed &lt;/font&gt;modifier. Use of this modifier prevents a derived class from further overriding the event. The accessors of a sealed event are also sealed.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;It is a compile-time error for an overriding event declaration to include a &lt;font face=&quot;Lucida Console&quot;&gt;new &lt;/font&gt;modifier.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/5815766097882699838/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/introduction-to-c-events.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/5815766097882699838'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/5815766097882699838'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/introduction-to-c-events.html' title='Introduction to C# Events'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-4250808315569495342</id><published>2012-02-11T04:32:00.001-08:00</published><updated>2012-02-11T08:13:28.171-08:00</updated><title type='text'>Introduction to C# Delegates</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;        p.msonormal        {            margin-top: 0in;            margin-right: 0in;            margin-bottom: 6.0pt;            margin-left: 0in;            font-size: 11.0pt;        }        span.codefragment        {            font-family: &quot;Lucida Console&quot;;        }        h2        {            margin-top: 8.0pt;            margin-right: 0in;            margin-bottom: 4.0pt;            margin-left: .4in;            text-indent: -.4in;            page-break-after: avoid;            font-size: 12.0pt;        }        span.production        {            font-style: italic;        }        p.grammar        {            margin-top: 0in;            margin-right: 0in;            margin-bottom: 6.0pt;            margin-left: .75in;            text-indent: -.25in;            line-height: 12.5pt;            font-size: 11.0pt;            font-style: italic;        }        span.terminal        {            font-family: &quot;Lucida Console&quot;;            font-style: italic;        }        p.code        {            margin-top: 0in;            margin-right: 0in;            margin-bottom: 6.0pt;            margin-left: .5in;            font-size: 10.0pt;            font-family: &quot;Lucida Console&quot;;        }        span.term        {            font-weight: bold;            font-style: italic;        }        p.msolistbullet        {            margin-top: 0in;            margin-right: 0in;            margin-bottom: 6.0pt;            margin-left: .25in;            text-indent: -.25in;            tab-stops: list .25in;            font-size: 11.0pt;        }        div.wordsection1        {            page: wordsection1;        }    &lt;/style&gt;  &lt;div class=&quot;WordSection1&quot;&gt; &lt;p align=&quot;justify&quot;&gt;Delegates enable scenarios that other languages such as C++, Pascal, and Modula have addressed with function pointers. Unlike C++ function pointers, however, delegates are fully object oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;A delegate declaration defines a class that is derived from the class &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;System.Delegate&lt;/span&gt;&lt;/span&gt;. A delegate instance encapsulates an invocation list, which is a list of one or more methods, each of which is referred to as a callable entity. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method. Invoking a delegate instance with an appropriate set of arguments causes each of the delegate’s callable entities to be invoked with the given set of arguments.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;An interesting and useful property of a delegate instance is that it does not know or care about the classes of the methods it encapsulates; all that matters is that those methods be compatible with the delegate’s type. This makes delegates perfectly suited for “anonymous” invocation.&lt;/p&gt; &lt;h2&gt;&lt;a name=&quot;_Toc445783089&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref451394461&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref493151493&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref495219206&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508191585&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508192744&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508432331&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508600674&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508600694&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref513725258&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref12502422&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref155511458&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref171237638&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc251613414&quot;&gt;Delegate declarations&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p class=&quot;MsoNormal&quot;&gt;A &lt;span class=&quot;Production&quot;&gt;delegate-declaration&lt;/span&gt; is a &lt;span class=&quot;Production&quot;&gt;type-declaration&lt;/span&gt; that declares a new delegate type.&lt;/p&gt; &lt;blockquote&gt; &lt;p class=&quot;Grammar&quot;&gt;&lt;strong&gt;delegate-declaration:&lt;/strong&gt;&lt;br&gt;&lt;em&gt;attributes &lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;delegate&lt;/font&gt; &lt;/span&gt;&lt;/span&gt;return-type&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;(&lt;/span&gt;&lt;/span&gt;formal-parameter-list&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;)&lt;/span&gt;&lt;/span&gt;&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;;&lt;/span&gt;&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;blockquote&gt; &lt;p class=&quot;Grammar&quot;&gt;&lt;strong&gt;delegate-modifier:&lt;br&gt;&lt;/strong&gt;&lt;font face=&quot;Lucida Console&quot;&gt;&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;new&lt;/span&gt;&lt;/span&gt;&lt;br&gt;&lt;/font&gt;&lt;font face=&quot;Lucida Console&quot;&gt;&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;public&lt;br&gt;protected&lt;br&gt;internal&lt;/span&gt;&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;Terminal&quot;&gt;&lt;span style=&quot;font-style: normal; font-size: 10pt&quot;&gt;private&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;It is a compile-time error for the same modifier to appear multiple times in a delegate declaration.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;new&lt;/font&gt;&lt;/span&gt;&lt;/span&gt; modifier is only permitted on delegates declared within another type, in which case it specifies that such a delegate hides an inherited member by the same name.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;The optional &lt;span class=&quot;Production&quot;&gt;formal-parameter-list&lt;/span&gt; specifies the parameters of the delegate, and &lt;span class=&quot;Production&quot;&gt;return-type&lt;/span&gt; indicates the return type of the delegate. &lt;/p&gt; &lt;p&gt;The return type of a delegate type must be either &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;void&lt;/span&gt;&lt;/span&gt;, or output-safe.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;All the formal parameter types of a delegate type must be input-safe. Additionally, any &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;out&lt;/span&gt;&lt;/span&gt; or &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;ref&lt;/span&gt;&lt;/span&gt; parameter types must also be output-safe. Note that even &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;out&lt;/span&gt;&lt;/span&gt; parameters are required to be input-safe, due to a limitation of the underlying execution platform.&lt;/p&gt; &lt;p align=&quot;justify&quot;&gt;Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types. However, instances of two distinct but structurally equivalent delegate types may compare as equal.&lt;/p&gt; &lt;p&gt;For example:&lt;/p&gt;&lt;pre&gt;delegate int D1(int i, double d);&lt;br /&gt;&lt;br /&gt;class A&lt;br /&gt;{&lt;br /&gt;      public static int M1(int a, double b) {...}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class B&lt;br /&gt;{&lt;br /&gt;      delegate int D2(int c, double d);&lt;br /&gt;      public static int M1(int f, double g) {...}&lt;br /&gt;      public static void M2(int k, double l) {...}&lt;br /&gt;      public static int M3(int g) {...}&lt;br /&gt;      public static void M4(int g) {...}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;The delegate types &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D1&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D2&lt;/span&gt;&lt;/span&gt; are both compatible with the methods &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;A.M1&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;B.M1&lt;/span&gt;&lt;/span&gt;, since they have the same return type and parameter list; however, these delegate types are two different types, so they are not interchangeable. The delegate types &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D1&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D2&lt;/span&gt;&lt;/span&gt; are incompatible with the methods &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;B.M2&lt;/span&gt;&lt;/span&gt;, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;B.M3&lt;/span&gt;&lt;/span&gt;, and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;B.M4&lt;/span&gt;&lt;/span&gt;, since they have different return types or parameter lists.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;Like other generic type declarations, type arguments must be given to create a constructed delegate type. The parameter types and return type of a constructed delegate type are created by substituting, for each type parameter in the delegate declaration, the corresponding type argument of the constructed delegate type. The resulting return type and parameter types are used in determining what methods are compatible with a constructed delegate type. For example:&lt;/p&gt;&lt;pre&gt;delegate bool Predicate&lt;t&gt;(T value);&lt;br /&gt;&lt;br /&gt;class X&lt;br /&gt;{&lt;br /&gt;      static bool F(int i) {...}&lt;br /&gt;      static bool G(string s) {...}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p class=&quot;Code&quot;&gt;The delegate type &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;Predicate&amp;lt;int&amp;gt;&lt;/font&gt;&lt;/span&gt;&lt;/span&gt; is compatible with the method &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;X.F&lt;/span&gt;&lt;/span&gt; and the delegate type &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;Predicate&amp;lt;string&amp;gt;&lt;/font&gt;&lt;/span&gt;&lt;/span&gt; is compatible with the method &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;X.G&lt;/span&gt;&lt;/span&gt;.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;The only way to declare a delegate type is via a &lt;span class=&quot;Production&quot;&gt;delegate-declaration&lt;/span&gt;. A delegate type is a class type that is derived from &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;System.Delegate&lt;/font&gt;&lt;/span&gt;&lt;/span&gt;. Delegate types are implicitly &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;sealed&lt;/span&gt;&lt;/span&gt;, so it is not permissible to derive any type from a delegate type. It is also not permissible to derive a non-delegate class type from &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;System.Delegate&lt;/font&gt;&lt;/span&gt;&lt;/span&gt;. Note that &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;&lt;font face=&quot;Lucida Console&quot;&gt;System.Delegate&lt;/font&gt;&lt;/span&gt;&lt;/span&gt; is not itself a delegate type; it is a class type from which all delegate types are derived.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;C# provides special syntax for delegate instantiation and invocation. Except for instantiation, any operation that can be applied to a class or class instance can also be applied to a delegate class or instance, respectively. In particular, it is possible to access members of the &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;System.Delegate&lt;/span&gt;&lt;/span&gt; type via the usual member access syntax.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;The set of methods encapsulated by a delegate instance is called an invocation list. When a delegate instance is created from a single method, it encapsulates that method, and its invocation list contains only one entry. However, when two non-null delegate instances are combined, their invocation lists are concatenated—in the order left operand then right operand—to form a new invocation list, which contains two or more entries.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;Delegates are combined using the binary &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;+&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;+=&lt;/span&gt;&lt;/span&gt; operators. A delegate can be removed from a combination of delegates, using the binary &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;-&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;-=&lt;/span&gt;&lt;/span&gt; operators. Delegates can be compared for equality.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;The following example shows the instantiation of a number of delegates, and their corresponding invocation lists:&lt;/p&gt;&lt;pre&gt;delegate void D(int x);&lt;br /&gt;&lt;br /&gt;class C&lt;br /&gt;{&lt;br /&gt;    public static void M1(int i) {...}&lt;br /&gt;    public static void M2(int i) {...}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Test&lt;br /&gt;{&lt;br /&gt;    static void Main () &lt;br /&gt;    {&lt;br /&gt;        D cd1 = new D(C.M1);          // M1&lt;br /&gt;        D cd2 = new D(C.M2);          // M2&lt;br /&gt;        D cd3 = cd1 + cd2;            // M1 + M2&lt;br /&gt;        D cd4 = cd3 + cd1;            // M1 + M2 + M1&lt;br /&gt;        D cd5 = cd4 + cd3;            // M1 + M2 + M1 + M1 + M2&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;When &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd1&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd2&lt;/span&gt;&lt;/span&gt; are instantiated, they each encapsulate one method. When &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd3&lt;/span&gt;&lt;/span&gt; is instantiated, it has an invocation list of two methods, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M2&lt;/span&gt;&lt;/span&gt;, in that order. &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd4&lt;/span&gt;&lt;/span&gt;’s invocation list contains &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt;, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M2&lt;/span&gt;&lt;/span&gt;, and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt;, in that order. Finally, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd5&lt;/span&gt;&lt;/span&gt;’s invocation list contains &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt;, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M2&lt;/span&gt;&lt;/span&gt;, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt;, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M1&lt;/span&gt;&lt;/span&gt;, and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M2&lt;/span&gt;&lt;/span&gt;, in that order. For more examples of combining (as well as removing) delegates.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;&lt;a name=&quot;_Ref174224038&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc251613415&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;Delegate compatibility&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/h2&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;A method or delegate &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt; is &lt;span class=&quot;Term&quot;&gt;compatible&lt;/span&gt; with a &lt;st1:state w:st=&quot;on&quot;&gt;&lt;st1:place w:st=&quot;on&quot;&gt;del&lt;/st1:place&gt;&lt;/st1:state&gt;egate type &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt; if all of the following are true:&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt; and &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt; have the same number of parameters, and each parameter in &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt; has the same &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;ref&lt;/span&gt;&lt;/span&gt; or &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;out&lt;/span&gt;&lt;/span&gt; modifiers as the corresponding parameter in &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;For each value parameter (a parameter with no &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;ref&lt;/span&gt;&lt;/span&gt; or &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;out&lt;/span&gt;&lt;/span&gt; modifier), an identity conversion or implicit reference conversion &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;exists from the parameter type in &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt; to the corresponding parameter type in &lt;/span&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;For each &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;ref&lt;/span&gt;&lt;/span&gt; or &lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;out&lt;/span&gt;&lt;/span&gt; parameter, the parameter type in &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt; is the same as the parameter type in &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;An identity or implicit reference conversion exists from the return type of &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;M&lt;/span&gt;&lt;/span&gt; to the return type of &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;D&lt;/span&gt;&lt;/span&gt;.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;h2&gt;&lt;span style=&quot;mso-bookmark: _toc486309875&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref508433325&quot;&gt;&lt;a name=&quot;_Toc251613416&quot;&gt;Delegate instantiation&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;/h2&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;An instance of a delegate is created by a &lt;span class=&quot;Production&quot;&gt;delegate-creation-expression&lt;/span&gt; or a conversion to a delegate type. The newly created delegate instance then refers to either:&lt;/p&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot;&gt;The static method referenced in the &lt;span class=&quot;Production&quot;&gt;delegate-creation-expression&lt;/span&gt;, or&lt;/div&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot;&gt;The target object (which cannot be &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;null&lt;/span&gt;&lt;/span&gt;) and instance method referenced in the &lt;span class=&quot;Production&quot;&gt;delegate-creation-expression&lt;/span&gt;, or&lt;/div&gt;&lt;br /&gt;&lt;li&gt;&lt;br /&gt;&lt;div class=&quot;MsoListBullet&quot;&gt;Another delegate.&lt;/div&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot;&gt;For example:&lt;/p&gt;&lt;pre&gt;delegate void D(int x);&lt;br /&gt;&lt;br /&gt;class C&lt;br /&gt;{&lt;br /&gt;    public static void M1(int i) {...}&lt;br /&gt;    public void M2(int i) {...}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Test&lt;br /&gt;{&lt;br /&gt;    static void Main () &lt;br /&gt;    { &lt;br /&gt;        D cd1 = new D(C.M1);          // static method&lt;br /&gt;        C t = new C();&lt;br /&gt;        D cd2 = new D(t.M2);          // instance method&lt;br /&gt;        D cd3 = new D(cd2);           // another delegate&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p class=&quot;Code&quot;&gt;&lt;span style=&quot;mso-ansi-language: no-bok&quot; lang=&quot;NO-BOK&quot;&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;Code&quot; align=&quot;justify&quot;&gt;Once instantiated, delegate instances always refer to the same target object and method. Remember, when two delegates are combined, or one is removed from another, a new delegate results with its own invocation list; the invocation lists of the delegates combined or removed remain unchanged.&lt;/p&gt;&lt;br /&gt;&lt;h2&gt;&lt;a name=&quot;_Ref485628540&quot;&gt;&lt;/a&gt;&lt;a name=&quot;_Toc251613417&quot;&gt;&lt;/a&gt;&lt;a name=&quot;_Ref5435980&quot;&gt;&lt;/a&gt;&lt;a name=&quot;_Ref513725642&quot;&gt;&lt;/a&gt;&lt;a name=&quot;_Toc486309877&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref513725642&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref5435980&quot;&gt;&lt;span style=&quot;mso-bookmark: _toc251613417&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;Delegate invocation&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;/h2&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;C# provides special syntax for invoking a delegate. When a non-null delegate instance whose invocation list contains one entry is invoked, it invokes the one method with the same arguments it was given, and returns the same value as the referred to method. &lt;/span&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;If an exception occurs during the invocation of such a delegate, and that exception is not caught within the method that was invoked, the search for an exception catch clause continues in the method that called the delegate, as if that method had directly called the method to which that delegate referred.&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. Each method so called is passed the same set of arguments as was given to the delegate instance. If such a delegate invocation includes reference parameters&lt;/span&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;, each method invocation will occur with a reference to the same variable; changes to that variable by one method in the invocation list will be visible to methods further down the invocation list. If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;&lt;span style=&quot;mso-bookmark: _ref485628540&quot;&gt;If an exception occurs during processing of the invocation of such a delegate, and that exception is not caught within the method that was invoked, the search for an exception catch clause continues in the method that called the delegate, and any methods further down the invocation list are not invoked.&lt;/span&gt;&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;Attempting to invoke a delegate instance whose value is null results in an exception of type &lt;font face=&quot;Lucida Console&quot;&gt;&lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;System.NullReferenceException&lt;/span&gt;&lt;/span&gt;.&lt;/font&gt;&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;The following example shows how to instantiate, combine, remove, and invoke delegates:&lt;/p&gt;&lt;pre&gt;using System;&lt;br /&gt;&lt;br /&gt;delegate void D(int x);&lt;br /&gt;&lt;br /&gt;class C&lt;br /&gt;{&lt;br /&gt;    public static void M1(int i)&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(&quot;C.M1: &quot; + i);&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    public static void M2(int i) &lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(&quot;C.M2: &quot; + i);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public void M3(int i) &lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(&quot;C.M3: &quot; + i);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class Test&lt;br /&gt;{&lt;br /&gt;    static void Main () &lt;br /&gt;    { &lt;br /&gt;        D cd1 = new D(C.M1);&lt;br /&gt;        cd1(-1);                  // call M1&lt;br /&gt;&lt;br /&gt;        D cd2 = new D(C.M2);&lt;br /&gt;        cd2(-2);                  // call M2&lt;br /&gt;&lt;br /&gt;        D cd3 = cd1 + cd2;&lt;br /&gt;        cd3(10);                  // call M1 then M2&lt;br /&gt;&lt;br /&gt;        cd3 += cd1;&lt;br /&gt;        cd3(20);                  // call M1, M2, then M1&lt;br /&gt;&lt;br /&gt;        C c = new C();&lt;br /&gt;        D cd4 = new D(c.M3);&lt;br /&gt;        cd3 += cd4;&lt;br /&gt;        cd3(30);                  // call M1, M2, M1, then M3&lt;br /&gt;&lt;br /&gt;        cd3 -= cd1;         // remove last M1&lt;br /&gt;        cd3(40);                  // call M1, M2, then M3&lt;br /&gt;&lt;br /&gt;        cd3 -= cd4;&lt;br /&gt;        cd3(50);                  // call M1 then M2&lt;br /&gt;&lt;br /&gt;        cd3 -= cd2;&lt;br /&gt;        cd3(60);                  // call M1&lt;br /&gt;&lt;br /&gt;        cd3 -= cd2;         // impossible removal is benign&lt;br /&gt;        cd3(60);                  // call M1&lt;br /&gt;&lt;br /&gt;        cd3 -= cd1;         // invocation list is empty so cd3 is null&lt;br /&gt;        //          cd3(70);          // System.NullReferenceException thrown&lt;br /&gt;&lt;br /&gt;        cd3 -= cd1;         // impossible removal is benign&lt;br /&gt;      }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;p class=&quot;Code&quot; align=&quot;justify&quot;&gt;As shown in the statement &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd3 += cd1;&lt;/span&gt;&lt;/span&gt;, a delegate can be present in an invocation list multiple times. In this case, it is simply invoked once per occurrence. In an invocation list such as this, when that delegate is removed, the last occurrence in the invocation list is the one actually removed.&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot; align=&quot;justify&quot;&gt;Immediately prior to the execution of the final statement, &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd3 -= cd1;&lt;/span&gt;&lt;/span&gt;, the delegate &lt;span class=&quot;Codefragment&quot;&gt;&lt;span style=&quot;font-size: 10pt&quot;&gt;cd3&lt;/span&gt;&lt;/span&gt; refers to an empty invocation list. Attempting to remove a delegate from an empty list (or to remove a non-existent delegate from a non-empty list) is not an error. &lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;MsoNormal&quot;&gt;The output produced is:&lt;/p&gt;&lt;br /&gt;&lt;p class=&quot;Code&quot;&gt;C.M1: -1&lt;br&gt;C.M2: -2&lt;br&gt;C.M1: 10&lt;br&gt;C.M2: 10&lt;br&gt;C.M1: 20&lt;br&gt;C.M2: 20&lt;br&gt;C.M1: 20&lt;br&gt;C.M1: 30&lt;br&gt;C.M2: 30&lt;br&gt;C.M1: 30&lt;br&gt;C.M3: 30&lt;br&gt;C.M1: 40&lt;br&gt;C.M2: 40&lt;br&gt;C.M3: 40&lt;br&gt;C.M1: 50&lt;br&gt;C.M2: 50&lt;br&gt;C.M1: 60&lt;br&gt;C.M1: 60&lt;/p&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/4250808315569495342/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/delegates.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/4250808315569495342'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/4250808315569495342'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/delegates.html' title='Introduction to C# Delegates'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3977111882153719926.post-7916832202021405154</id><published>2012-02-11T01:05:00.000-08:00</published><updated>2012-02-11T02:33:00.896-08:00</updated><title type='text'>Introduction to C# Generics (MSDN)</title><content type='html'>&lt;p&gt;
    &lt;strong&gt;Summary:&lt;/strong&gt; This article discusses the problem space generics 
    address, how they are implemented, the benefits of the programming model, and 
    unique innovations, such as constrains, generic methods and delegates, and 
    generic inheritance. In addition it discusses how the .NET Framework utilizes 
    generics (45 pages)&lt;/p&gt;
&lt;h4 class=&quot;dtH1&quot;&gt;
    Contents&lt;/h4&gt;
&lt;p&gt;
    &lt;a href=&quot;#csharp_generics_topica&quot;&gt;
    Introduction&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic1&quot;&gt;
    Generics Problem Statement&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic2&quot;&gt;
    What Are Generics&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic3&quot;&gt;
    Applying Generics&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic4&quot;&gt;
    Generic Constraints &lt;/a&gt;
    &lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic5&quot;&gt;
    Generics and Casting&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic6&quot;&gt;
    Inheritance and Generics&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic7&quot;&gt;
    Generic Methods&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic8&quot;&gt;
    Generic Delegates&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic9&quot;&gt;
    Generics and Reflection&lt;/a&gt;&lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic10&quot;&gt;
    Generics and the .NET Framework &lt;/a&gt;
    &lt;br /&gt;
    &lt;a href=&quot;#csharp_generics_topic11&quot;&gt;
    Conclusion&lt;/a&gt;&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topica&quot;&gt;&lt;/a&gt;Introduction&lt;/h2&gt;
&lt;p&gt;
    Generics are the most powerful feature of C# 2.0. Generics allow you to define 
    type-safe data structures, without committing to actual data types. This results 
    in a significant performance boost and higher quality code, because you get to 
    reuse data processing algorithms without duplicating type-specific code. In 
    concept, generics are similar to C++ templates, but are drastically different in 
    implementation and capabilities. This article discusses the problem space 
    generics address, how they are implemented, the benefits of the programming 
    model, and unique innovations, such as constrains, generic methods and 
    delegates, and generic inheritance. You will also see how generics are utilized 
    in other areas of the .NET Framework such as reflection, arrays, collections, 
    serialization, and remoting, and how to improve on the basic offering.
&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic1&quot;&gt;&lt;/a&gt;Generics Problem Statement&lt;/h2&gt;
&lt;p&gt;
    Consider an everyday data structure such as a stack, providing the classic
    &lt;strong&gt;Push()&lt;/strong&gt; and &lt;strong&gt;Pop()&lt;/strong&gt; methods. When developing a 
    general-purpose stack, you would like to use it to store instances of various 
    types. Under C# 1.1, you have to use an Object-based stack, meaning that the 
    internal data type used in the stack is an amorphous Object, and the stack 
    methods interact with Objects:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Stack
{
   object[] m_Items; 
   public void Push(object item)
   {...}
   public object Pop()
   {...}
}&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 1&lt;/strong&gt; shows the full implementation of the Object-based 
    stack. Because Object is the canonical .NET base type, you can use the 
    Object-based stack to hold any type of items, such as integers:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
int number = (int)stack.Pop();
&lt;/pre&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 1. An Object-based stack&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Stack
{
   readonly int m_Size; 
   int m_StackPointer = 0;
   object[] m_Items; 
   public Stack():this(100)
   {}   
   public Stack(int size)
   {
      m_Size = size;
      m_Items = new object[m_Size];
   }
   public void Push(object item)
   {
      if(m_StackPointer &amp;gt;= m_Size) 
         throw new StackOverflowException();       
      m_Items[m_StackPointer] = item;
      m_StackPointer++;
   }
   public object Pop()
   {
      m_StackPointer--;
      if(m_StackPointer &amp;gt;= 0)
      {
         return m_Items[m_StackPointer];
      }
      else
      {
         m_StackPointer = 0;
         throw new InvalidOperationException(&amp;quot;Cannot pop an empty stack&amp;quot;);
      }
   }
}
&lt;/pre&gt;
&lt;p&gt;
    However, there are two problems with Object-based solutions. The first issue is 
    performance. When using value types, you have to box them in order to push and 
    store them, and unbox the value types when popping them off the stack. Boxing 
    and unboxing incurs a significant performance penalty in their own right, but it 
    also increases the pressure on the managed heap, resulting in more garbage 
    collections, which is not great for performance either. Even when using 
    reference types instead of value types, there is still a performance penalty 
    because you have to cast from an Object to the actual type you interact with and 
    incur the casting cost:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Stack stack = new Stack();
stack.Push(&amp;quot;1&amp;quot;);
string number = &lt;strong&gt;(string)&lt;/strong&gt;stack.Pop();
&lt;/pre&gt;
&lt;p&gt;
    The second (and often more severe) problem with the Object-based solution is 
    type safety. Because the compiler lets you cast anything to and from Object, you 
    lose compile-time type safety. For example, the following code compiles fine, 
    but raises an invalid cast exception at run time:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Stack stack = new Stack();
stack.Push(1);
//This compiles, but is not type safe, and will throw an exception: 
string number = (string)stack.Pop();
&lt;/pre&gt;
&lt;p&gt;
    You can overcome these two problems by providing a type-specific (and hence, 
    type-safe) performant stack. For integers you can implement and use the &lt;strong&gt;
    IntStack&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class IntStack
{
   int[] m_Items; 
   public void Push(int item){...}
   public int Pop(){...}
} 
IntStack stack = new IntStack();
stack.Push(1);
int number = stack.Pop();
&lt;/pre&gt;
&lt;p&gt;
    For strings you would implement the &lt;strong&gt;StringStack&lt;/strong&gt;:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class StringStack
{
   string[] m_Items; 
   public void Push(string item){...}
   public string Pop(){...}
}
StringStack stack = new StringStack();
stack.Push(&amp;quot;1&amp;quot;);
string number = stack.Pop();
&lt;/pre&gt;
&lt;p&gt;
    And so on. Unfortunately, solving the performance and type-safety problems this 
    way introduces a third, and just as serious problem—productivity impact. Writing 
    type-specific data structures is a tedious, repetitive, and error-prone task. 
    When fixing a defect in the data structure, you have to fix it not just in one 
    place, but in as many places as there are type-specific duplicates of what is 
    essentially the same data structure. In addition, there is no way to foresee the 
    use of unknown or yet-undefined future types, so you have to keep an 
    Object-based data structure as well. As a result, most C# 1.1 developers found 
    type-specific data structures to be impractical and opt for using Object-based 
    data structures, in spite of their deficiencies.
&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic2&quot;&gt;&lt;/a&gt;What Are Generics&lt;/h2&gt;
&lt;p&gt;
    Generics allow you to define type-safe classes without compromising type safety, 
    performance, or productivity. You implement the server only once as a generic 
    server, while at the same time you can declare and use it with any type. To do 
    that, use the &lt;strong&gt;&amp;lt;&lt;/strong&gt; and &lt;strong&gt;&amp;gt;&lt;/strong&gt; brackets, enclosing a 
    generic type parameter. For example, here is how you define and use a generic 
    stack:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Stack&amp;lt;T&amp;gt;
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack&amp;lt;int&amp;gt; stack = new Stack&amp;lt;int&amp;gt;();
stack.Push(1);
stack.Push(2);
int number = stack.Pop();
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 2&lt;/strong&gt; shows the full implementation of the generic 
    stack. Compare &lt;strong&gt;Code block 1&lt;/strong&gt; to &lt;strong&gt;Code block 2&lt;/strong&gt; 
    and see that it is as if every use of &lt;code class=&quot;ce&quot;&gt;object&lt;/code&gt; in &lt;strong&gt;
    Code block 1&lt;/strong&gt; is replaced with &lt;code class=&quot;ce&quot;&gt;T&lt;/code&gt; in &lt;strong&gt;Code 
    block 2&lt;/strong&gt;, except that the Stack is defined using the generic type 
    parameter T:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Stack&amp;lt;T&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    When using a generic stack, you have to instruct the compiler which type to use 
    instead of the generic type parameter T, both when declaring the variable and 
    when instantiating it:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Stack&amp;lt;int&amp;gt; stack = new Stack&amp;lt;int&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;
    The compiler and the runtime do the rest. All the methods (or properties) that 
    accept or return a T will instead use the specified type, an integer in the 
    example above.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 2. The generic stack&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Stack&amp;lt;T&amp;gt;
{
   readonly int m_Size; 
   int m_StackPointer = 0;
   T[] m_Items;
   public Stack():this(100)
   {}
   public Stack(int size)
   {
      m_Size = size;
      m_Items = new T[m_Size];
   }
   public void Push(T item)
   {
      if(m_StackPointer &amp;gt;= m_Size) 
         throw new StackOverflowException();
      m_Items[m_StackPointer] = item;
      m_StackPointer++;
   }
   public T Pop()
   {
      m_StackPointer--;
      if(m_StackPointer &amp;gt;= 0)
      {
         return m_Items[m_StackPointer];
      }
      else
      {
         m_StackPointer = 0;
         throw new InvalidOperationException(&amp;quot;Cannot pop an empty stack&amp;quot;);
      }
   }
}
&lt;/pre&gt;
&lt;blockquote class=&quot;dtBlock&quot;&gt;
    &lt;strong&gt;Note&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/strong&gt;T is the generic type parameter (or type parameter) 
    while the generic type is the Stack&amp;lt;T&amp;gt;. The int in Stack&amp;lt;int&amp;gt; is the type 
    argument.
&lt;/blockquote&gt;
&lt;p&gt;
    The advantage of this programming model is that the internal algorithms and data 
    manipulation remain the same while the actual data type can change based on the 
    way the client uses your server code.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Generics Implementation&lt;/h3&gt;
&lt;p&gt;
    On the surface C# generics look syntactically similar to C++ templates, but 
    there are important differences in the way they are implemented and supported by 
    the compiler. As you will see later in this article, this has significant 
    implications on the manner in which you use generics.
&lt;/p&gt;
&lt;blockquote class=&quot;dtBlock&quot;&gt;
    &lt;strong&gt;Note&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/strong&gt;In the context of this article, when referring to C++ it 
    means classic C++, not Microsoft C++ with the managed extensions.&lt;/blockquote&gt;
&lt;p&gt;
    Compared to C++ templates, C# generics can provide enhanced safety but are also 
    somewhat limited in capabilities.
&lt;/p&gt;
&lt;p&gt;
    In some C++ compilers, until you use a template class with a specific type, the 
    compiler does not even compile the template code. When you do specify a type, 
    the compiler inserts the code inline, replacing every occurrence of the generic 
    type parameter with the specified type. In addition, every time you use a 
    specific type, the compiler inserts the type-specific code, regardless of 
    whether you have already specified that type for the template class somewhere 
    else in the application. It is up to the C++ linker to resolve this, and it is 
    not always possible to do. This may results in code bloating, increasing both 
    the load time and the memory footprint.
&lt;/p&gt;
&lt;p&gt;
    In .NET 2.0, generics have native support in IL (intermediate language) and the 
    CLR itself. When you compile generic C# server-side code, the compiler compiles 
    it into IL, just like any other type. However, the IL only contains parameters 
    or place holders for the actual specific types. In addition, the metadata of the 
    generic server contains generic information.
&lt;/p&gt;
&lt;p&gt;
    The client-side compiler uses that generic metadata to support type safety. When 
    the client provides a specific type instead of a generic type parameter, the 
    client&amp;#39;s compiler substitutes the generic type parameter in the server metadata 
    with the specified type argument. This provides the client&amp;#39;s compiler with 
    type-specific definition of the server, as if generics were never involved. This 
    way the client compiler can enforce correct method parameters, type-safety 
    checks, and even type-specific IntelliSense.
&lt;/p&gt;
&lt;p&gt;
    The interesting question is how does .NET compile the generic IL of the server 
    to machine code. It turns out that the actual machine code produced depends on 
    whether the specified types are value or reference type. If the client specifies 
    a value type, then the JIT compiler replaces the generic type parameters in the 
    IL with the specific value type, and compiles it to native code. However, the 
    JIT compiler keeps track of type-specific server code it already generated. If 
    the JIT compiler is asked to compile the generic server with a value type it has 
    already compiled to machine code, it simply returns a reference to that server 
    code. Because the JIT compiler uses the same value-type-specific server code in 
    all further encounters, there is no code bloating.
&lt;/p&gt;
&lt;p&gt;
    If the client specifies a reference type, then the JIT compiler replaces the 
    generic parameters in the server IL with Object, and compiles it into native 
    code. That code will be used in any further request for a reference type instead 
    of a generic type parameter. Note that this way the JIT compiler only reuses 
    actual code. Instances are still allocated according to their size off the 
    managed heap, and there is no casting.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Generics Benefits&lt;/h3&gt;
&lt;p&gt;
    Generics in .NET let you reuse code and the effort you put into implementing it. 
    The types and internal data can change without causing code bloat, regardless of 
    whether you are using value or reference types. You can develop, test, and 
    deploy your code once, reuse it with any type, including future types, all with 
    full compiler support and type safety. Because the generic code does not force 
    the boxing and unboxing of value types, or the down casting of reference types, 
    performance is greatly improved. With value types there is typically a 200 
    percent performance gain, and with reference types you can expect up to a 100 
    percent performance gain in accessing the type (of course, the application as a 
    whole may or may not experience any performance improvements). The source code 
    available with this article includes a micro-benchmark application, which 
    executes a stack in a tight loop. The application lets you experiment with value 
    and reference types on an Object-based stack and a generic stack, as well as 
    changing the number of loop iterations to see the effect generics have on 
    performance.
&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic3&quot;&gt;&lt;/a&gt;Applying Generics&lt;/h2&gt;
&lt;p&gt;
    Because of the native support for generics in the IL and the CLR, most 
    CLR-compliant language can take advantage of generic types. For example, here is 
    some Visual Basic .NET code that uses the generic stack of &lt;strong&gt;Code block 2&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Dim stack As Stack(Of Integer)
stack = new Stack(Of Integer)
stack.Push(3)
Dim number As Integer
number = stack.Pop()
&lt;/pre&gt;
&lt;p&gt;
    You can use generics in classes and in structs. Here is a useful generic point 
    struct:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public &lt;strong&gt;struct&lt;/strong&gt; Point&amp;lt;T&amp;gt;
{
   
   public T X;
   
   public T Y;
}
&lt;/pre&gt;
&lt;p&gt;
    You can use the generic point for integer coordinates, for example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Point&amp;lt;int&amp;gt; point;
point.X = 1;
point.Y = 2;
&lt;/pre&gt;
&lt;p&gt;
    Or for charting coordinates that require floating point precision:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Point&amp;lt;double&amp;gt; point;
point.X = 1.2;
point.Y = 3.4;
&lt;/pre&gt;
&lt;p&gt;
    Besides the basic generics syntax presented so far, C# 2.0 has some 
    generics-specific syntax. For example, consider the &lt;strong&gt;Pop()&lt;/strong&gt; 
    method of &lt;strong&gt;Code block 2&lt;/strong&gt;. Suppose instead of throwing an 
    exception when the stack is empty, you would like to return the default value of 
    the type stored in the stack. If you were using an Object-based stack, you would 
    simply return null, but a generic stack could be used with value types as well. 
    To address this issue, you can use the &lt;strong&gt;default()&lt;/strong&gt; operator, 
    which returns the default value of a type.
&lt;/p&gt;
&lt;p&gt;
    Here is how you can use default in the implementation of the &lt;strong&gt;Pop()&lt;/strong&gt; 
    method:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public T Pop()
{
   m_StackPointer--;
   if(m_StackPointer &amp;gt;= 0)
   {
      return m_Items[m_StackPointer];
   }
   else
   {
      m_StackPointer = 0;
      return &lt;strong&gt;default(T)&lt;/strong&gt;;
   }
}
&lt;/pre&gt;
&lt;p&gt;
    The default value for reference types is null, and the default value for value 
    types (such as integers, enum, and structures) is a zero whitewash (filling the 
    structure with zeros). Consequently, if the stack is constructed with strings, 
    the &lt;strong&gt;Pop()&lt;/strong&gt; methods return null when the stack is empty, and when 
    the stack is constructed with integers, the &lt;strong&gt;Pop()&lt;/strong&gt; methods 
    return zero when the stack is empty.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Multiple Generic Types&lt;/h3&gt;
&lt;p&gt;
    A single type can define multiple generic-type parameters. For example, consider 
    the generic linked list shown in &lt;strong&gt;Code block 3&lt;/strong&gt;.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 3. Generic linked list&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;class Node&amp;lt;K,T&amp;gt;
{
   public K Key;
   public T Item;
   public Node&amp;lt;K,T&amp;gt; NextNode;
   public Node()
   {
      Key      = default(K);
      Item     = defualt(T);
      NextNode = null;
   }
   public Node(K key,T item,Node&amp;lt;K,T&amp;gt; nextNode)
   {
      Key      = key;
      Item     = item;
      NextNode = nextNode;
   }
}

public class LinkedList&amp;lt;K,T&amp;gt;
{
   Node&amp;lt;K,T&amp;gt; m_Head;
   public LinkedList()
   {
      m_Head = new Node&amp;lt;K,T&amp;gt;();
   }
   public void AddHead(K key,T item)
   {
      Node&amp;lt;K,T&amp;gt; newNode = new Node&amp;lt;K,T&amp;gt;(key,item,m_Head.NextNode);
      m_Head.NextNode = newNode;
   }
}
&lt;/pre&gt;
&lt;p&gt;
    The linked list stores nodes:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;class Node&amp;lt;K,T&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    Each node contains a key (of the generic type parameter K) and a value (of the 
    generic type parameter T). Each node also has a reference to the next node in 
    the list. The linked list itself is defined in terms of the generic type 
    parameters K and T:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    This allows the list to expose generic methods like &lt;strong&gt;AddHead()&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public void AddHead(K key,T item);
&lt;/pre&gt;
&lt;p&gt;
    Whenever you declare a variable of a type that uses generics, you must specify 
    the types to use. However, the specified type arguments can themselves be 
    generic type parameters. For example, the linked list has a member variable 
    called m_Head of type Node, used for referencing the first item in the list. 
    m_Head is declared using the list&amp;#39;s own generic type parameters K and T&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Node&amp;lt;K,T&amp;gt; m_Head;
&lt;/pre&gt;
&lt;p&gt;
    You need to provide type arguments when instantiating a node, and again, you can 
    use the linked list&amp;#39;s own generic type parameters:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public void AddHead(K key,T item)
{
   Node&amp;lt;K,T&amp;gt; newNode = new Node&amp;lt;&lt;strong&gt;K,T&lt;/strong&gt;&amp;gt;(key,item,m_Head.NextNode);
   m_Head.NextNode = newNode;
}
&lt;/pre&gt;
&lt;p&gt;
    Note that the fact the list uses the same names as the node for the generic type 
    parameters is purely for readability purposes, and it could have used other 
    names, such as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;U,V&amp;gt;
{...}&lt;/pre&gt;
&lt;p&gt;
    Or:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;KeyType,DataType&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    In which case, m_Head would have been declared as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Node&amp;lt;KeyType,DataType&amp;gt; m_Head;
&lt;/pre&gt;
&lt;p&gt;
    When the client is using the linked list, the client has to provide type 
    arguments. The client can choose integers as keys and strings as data items:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&lt;strong&gt;&amp;lt;int,string&amp;gt; &lt;/strong&gt;list = new LinkedList&lt;strong&gt;&amp;lt;int,string&amp;gt;&lt;/strong&gt;();
list.AddHead(123,&amp;quot;AAA&amp;quot;);
&lt;/pre&gt;
&lt;p&gt;
    But the client can choose any other combination, such as a time stamp for keys:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&amp;lt;DateTime,string&amp;gt; list = new LinkedList&amp;lt;DateTime,string&amp;gt;();
list.AddHead(DateTime.Now,&amp;quot;AAA&amp;quot;);   
&lt;/pre&gt;
&lt;p&gt;
    Sometimes is it useful to alias a particular combination of specific types. You 
    can do that through the using statement, as shown in &lt;strong&gt;Code block 4&lt;/strong&gt;. 
    Note that the scope of aliasing is the scope of the file, so you have to repeat 
    aliasing across the project files in the same way you would with using 
    namespaces.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 4. Generic type aliasing&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;using &lt;strong&gt;List&lt;/strong&gt; = LinkedList&amp;lt;int,string&amp;gt;;

class ListClient
{
   static void Main(string[] args)
   {
      &lt;strong&gt;List&lt;/strong&gt; list = new &lt;strong&gt;List&lt;/strong&gt;();
      list.AddHead(123,&amp;quot;AAA&amp;quot;);
   }
}
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic4&quot;&gt;&lt;/a&gt;Generic Constraints&lt;/h2&gt;
&lt;p&gt;
    With C# generics, the compiler compiles the generic code into IL independent of 
    any type arguments that the clients will use. As a result, the generic code 
    could try to use methods, properties, or members of the generic type parameters 
    that are incompatible with the specific type arguments the client uses. This is 
    unacceptable because it amounts to lack of type safety. In C# you need to 
    instruct the compiler which constraints the client-specified types must obey in 
    order for them to be used instead of the generic type parameters. There are 
    three types of constraints. A derivation constraint indicates to the compiler 
    that the generic type parameter derives from a base type such an interface or a 
    particular base class. A default constructor constraint indicates to the 
    compiler that the generic type parameter exposes a default public constructor (a 
    public constructor with no parameters). A reference/value type constraint 
    constrains the generic type parameter to be a reference or a value type. A 
    generic type can employ multiple constraints, and you even get IntelliSense 
    reflecting the constraints when using the generic type parameter, such as 
    suggesting methods or members from the base type.&lt;/p&gt;
&lt;p&gt;
    It is important to note that although constraints are optional, they are often 
    essential when developing a generic type. Without them, the compiler takes the 
    more conservative, type-safe approach and only allows access to Object-level 
    functionality in your generic type parameters. Constraints are part of the 
    generic type metadata so that the client-side compiler can take advantage of 
    them as well. The client-side compiler only allows the client developer to use 
    types that comply with the constraints, thus enforcing type safety.
&lt;/p&gt;
&lt;p&gt;
    An example will go a long way to explain the need and use of constraints. 
    Suppose you would like to add indexing ability or searching by key to the linked 
    list of &lt;strong&gt;Code block 3&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt;
{
   T Find(K key)
   {...}
   public T this[K key]
   {
      get{return Find(key);}
   }
}
&lt;/pre&gt;
&lt;p&gt;
    This allows the client to write the following code:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&lt;strong&gt;&amp;lt;int,string&amp;gt; &lt;/strong&gt;list = new LinkedList&lt;strong&gt;&amp;lt;int,string&amp;gt;&lt;/strong&gt;();

list.AddHead(123,&amp;quot;AAA&amp;quot;);
list.AddHead(456,&amp;quot;BBB&amp;quot;);
string item = list[456];
Debug.Assert(item == &amp;quot;BBB&amp;quot;);
&lt;/pre&gt;
&lt;p&gt;
    To implement the search, you need to scan the list, compare each node&amp;#39;s key with 
    the key you&amp;#39;re looking for, and return the item of the node whose key matches. 
    The problem is that the following implementation of &lt;strong&gt;Find()&lt;/strong&gt; does 
    not compile:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;T Find(K key)
{
   Node&amp;lt;K,T&amp;gt; current = m_Head;
   while(current.NextNode != null)
   {
      if(current.Key &lt;strong&gt;==&lt;/strong&gt; key) //Will not compile
         break;
      else
         
         current = current.NextNode;
   }
   return current.Item; 
}
&lt;/pre&gt;
&lt;p&gt;
    The reason is that the compiler will refuse to compile this line:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;if(current.Key &lt;strong&gt;==&lt;/strong&gt; key)
&lt;/pre&gt;
&lt;p&gt;
    The line above will not compile because the compiler does not know whether K (or 
    the actual type supplied by the client) supports the == operator. For example, 
    structs by default do not provide such an implementation. You could try to 
    overcome the == operator limitation by using the &lt;strong&gt;IComparable&lt;/strong&gt; 
    interface:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface IComparable 
{
   int CompareTo(object obj);
}
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;CompareTo()&lt;/strong&gt; returns 0 if the object you compare to is equal to 
    the object implementing the interface, so the &lt;strong&gt;Find()&lt;/strong&gt; method 
    could use it as follows:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;if(current.Key.&lt;strong&gt;CompareTo(key)&lt;/strong&gt; == 0)
&lt;/pre&gt;
&lt;p&gt;
    Unfortunately, this does not compile either because the compiler has no way of 
    knowing whether K (or the actual type supplied by the client) is derived from
    &lt;strong&gt;IComparable&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
    You could explicitly cast to &lt;strong&gt;IComparable&lt;/strong&gt; to force the compiler 
    to compile the comparing line, except doing so is at the expense of type safety:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;if((&lt;strong&gt;(IComparable)&lt;/strong&gt;(current.Key)).CompareTo(key) == 0)
&lt;/pre&gt;
&lt;p&gt;
    If the type the client uses does not derive from &lt;strong&gt;IComparable&lt;/strong&gt;, 
    it results in a run-time exception. In addition, when the key type used is a 
    value type instead of the key type parameter, you force a boxing of the key, and 
    that may have some performance implications.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Derivation Constraints&lt;/h3&gt;
&lt;p&gt;
    In C# 2.0 you use the &lt;strong&gt;where&lt;/strong&gt; reserved keyword to define a 
    constraint. Use the &lt;strong&gt;where&lt;/strong&gt; keyword on the generic type parameter 
    followed by a derivation colon to indicate to the compiler that the generic type 
    parameter implements a particular interface. For example, here is the derivation 
    constraint required to implement the &lt;strong&gt;Find() &lt;/strong&gt;method of 
    LinkedList:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; &lt;strong&gt;where K : IComparable&lt;/strong&gt;
{
   T Find(K key)
   {
      Node&amp;lt;K,T&amp;gt; current = m_Head;
      while(current.NextNode != null)
      {
         if(current.Key.&lt;strong&gt;CompareTo(key)&lt;/strong&gt; == 0)
            
            break;
         else      
            
            current = current.NextNode;
      }
      return current.Item; 
   }
   //Rest of the implementation 
}
&lt;/pre&gt;
&lt;p&gt;
    You will also get IntelliSense support on the methods of interfaces you 
    constrain.
&lt;/p&gt;
&lt;p&gt;
    When the client declares a variable of type &lt;strong&gt;LinkedList&lt;/strong&gt; 
    providing a type argument for the list&amp;#39;s key, the client-side compiler will 
    insist that the key type is derived from &lt;strong&gt;IComparable &lt;/strong&gt;and will 
    refuse to build the client code otherwise.
&lt;/p&gt;
&lt;p&gt;
    Note that even though the constraint allows you to use &lt;strong&gt;IComparable&lt;/strong&gt;, 
    it does not eliminate the boxing penalty when the key used is a value type, such 
    as an integer. To overcome this, the System.Collections.Generic namespace 
    defines the generic interface &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface IComparable&amp;lt;T&amp;gt; 
{
   int CompareTo(T other);
   bool Equals(T other);
}
&lt;/pre&gt;
&lt;p&gt;
    You can constrain the key type parameter to support &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt; 
    with the key&amp;#39;s type as the type parameter, and by doing so you gain not only 
    type safety but also eliminate the boxing of value types when used as keys:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; where K :&lt;strong&gt; IComparable&amp;lt;K&amp;gt;&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    In fact, all the types that supported &lt;strong&gt;IComparable&lt;/strong&gt; in .NET 1.1 
    support &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt; in .NET 2.0. This enables the use for 
    keys of common types such as int, string, Guid, DateTime, and so on.
&lt;/p&gt;
&lt;p&gt;
    In C# 2.0, all constraints must appear after the actual derivation list of the 
    generic class. For example, if &lt;strong&gt;LinkedList&lt;/strong&gt; derives from the
    &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; interface (for iterator support), you would put 
    the &lt;strong&gt;where&lt;/strong&gt; keyword immediately after it:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; : IEnumerable&amp;lt;T&amp;gt; where K : IComparable&amp;lt;K&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    In general, only define a constraint at the level where you require it. In the 
    linked list example, it is pointless to define the &lt;strong&gt;IComparable&amp;lt;T&amp;gt;&lt;/strong&gt; 
    derivation constraint at the node level, because the node itself does not 
    compare keys. If you do so, you will have to place the constraint at the &lt;strong&gt;
    LinkedList&lt;/strong&gt; level as well, even if the list does not compare keys. This 
    is because the list contains a node as a member variable, causing the compiler 
    to insist that the key type defined at the list level complies with the 
    constraint placed by the node on the generic key type.&lt;/p&gt;
&lt;p&gt;
    In other words, if you define the node as so:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;class Node&amp;lt;K,T&amp;gt;&lt;strong&gt; where K : IComparable&amp;lt;K&amp;gt;&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    Then you would have to repeat the constraint at the list level, even if you do 
    not provide the &lt;strong&gt;Find()&lt;/strong&gt; method, or any other method for that 
    matter:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;KeyType,DataType&amp;gt;&lt;strong&gt; where KeyType : IComparable&amp;lt;KeyType&amp;gt;&lt;/strong&gt;
{
   Node&amp;lt;&lt;strong&gt;KeyType&lt;/strong&gt;,DataType&amp;gt; m_Head;
}
&lt;/pre&gt;
&lt;p&gt;
    You can constrain multiple interfaces on the same generic type parameter, 
    separated by a comma. For example:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; where K : &lt;strong&gt;IComparable&amp;lt;K&amp;gt;,IConvertible&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    You can provide constraints for every generic type parameter your class uses, 
    for example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; &lt;strong&gt;where&lt;/strong&gt; K : IComparable&amp;lt;K&amp;gt;
&lt;strong&gt;                             where&lt;/strong&gt; T : ICloneable 
{...}
&lt;/pre&gt;
&lt;p&gt;
    You can have a base class constraint, meaning, stipulating that the generic type 
    parameter is derived from a particular base class:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyBaseClass
{...}
public class LinkedList&amp;lt;K,T&amp;gt; where K : &lt;strong&gt;MyBaseClass&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    However, at most one base class can be used in a constraint because C# does not 
    support multiple inheritance of implementation. Obviously, the base class you 
    constrain cannot be a sealed class or a static class, and the compiler enforces 
    that. In addition, you cannot constrain &lt;strong&gt;System.Delegate&lt;/strong&gt; or
    &lt;strong&gt;System.Array&lt;/strong&gt; as a base class.
&lt;/p&gt;
&lt;p&gt;
    You can constrain both a base class and one or more interfaces, but the base 
    class must appear first in the derivation constraint list:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; where K : &lt;strong&gt;MyBaseClass&lt;/strong&gt;, IComparable&amp;lt;K&amp;gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    C# does allow you to specify another generic type parameter as a constraint:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T,U&amp;gt; where T : &lt;strong&gt;U &lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    When dealing with a derivation constraint, you can satisfy the constraint using 
    the base type itself, not necessarily a strict sub class of it. For example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface IMyInterface
{...}
public class MyClass&amp;lt;T&amp;gt; where T : IMyInterface
{...}
MyClass&amp;lt;IMyInterface&amp;gt; obj = new MyClass&amp;lt;IMyInterface&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;
    Or even:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyOtherClass
{...}

public class MyClass&amp;lt;T&amp;gt; where T : MyOtherClass 
{...}

MyClass&amp;lt;MyOtherClass&amp;gt; obj = new MyClass&amp;lt;MyOtherClass&amp;gt;();&lt;/pre&gt;
&lt;p&gt;
    Finally, note that when providing a derivation constraint, the base type 
    (interface or base class) you constrain must have consistent visibility with 
    that of the generic type parameter you define. For instance, the following 
    constraint is valid, because internal types can use public types:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyBaseClass
{}
internal class MySubClass&amp;lt;T&amp;gt; where T : MyBaseClass
{}&lt;/pre&gt;
&lt;p&gt;
    However, if the visibility of the two classes were reversed, such as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;internal class MyBaseClass
{}
public class MySubClass&amp;lt;T&amp;gt; where T : MyBaseClass
{}
&lt;/pre&gt;
&lt;p&gt;
    Then the compiler would issue an error, because no client from outside the 
    assembly will ever be able to use the generic type &lt;strong&gt;MySubClass&lt;/strong&gt;, 
    rendering &lt;strong&gt;MySubClass&lt;/strong&gt; in effect as an internal rather than a 
    public type. The reason outside clients cannot use &lt;strong&gt;MySubClass&lt;/strong&gt; 
    is that to declare a variable of type &lt;strong&gt;MySubClass&lt;/strong&gt;, they require 
    to make use of a type that derives from the internal type &lt;strong&gt;MyBaseClass&lt;/strong&gt;.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Constructor Constraint
&lt;/h3&gt;
&lt;p&gt;
    Suppose you want to instantiate a new generic object inside a generic class. The 
    problem is the C# compiler does not know whether the type argument the client 
    will use has a matching constructor, and it will refuse to compile the 
    instantiation line.
&lt;/p&gt;
&lt;p&gt;
    To address this problem, C# allows you to constrain a generic type parameter 
    such that it must support a public default constructor. This is done using the
    &lt;strong&gt;new()&lt;/strong&gt; constraint. For example, here is a different way of 
    implementing the default constructor of the generic Node &amp;lt;K,T&amp;gt; from &lt;strong&gt;Code 
    block 3&lt;/strong&gt;.
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;class Node&amp;lt;K,T&amp;gt; where T : &lt;strong&gt;new()&lt;/strong&gt; 
{
   public K Key;
   public T Item;
   public Node&amp;lt;K,T&amp;gt; NextNode;
   public Node()
   {
      Key      = default(K);
      Item     = &lt;strong&gt;new T();&lt;/strong&gt;
      NextNode = null;
   }
}
&lt;/pre&gt;
&lt;p&gt;
    You can combine the constructor constraint with derivation constraint, provided 
    the constructor constraint appears last in the constraint list:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; where K : IComparable&amp;lt;K&amp;gt;,&lt;strong&gt;new() &lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Reference/Value Type Constraint&lt;/h3&gt;
&lt;p&gt;
    You can constrain a generic type parameter to be a value type (such as an int, a 
    bool, and enum) or any custom structure using the &lt;strong&gt;struct&lt;/strong&gt; 
    constraint:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt; where T : &lt;strong&gt;struct &lt;/strong&gt;

{...}
&lt;/pre&gt;
&lt;p&gt;
    Similarly, you can constrain a generic type parameter to be a reference type (a 
    class) using the &lt;strong&gt;class&lt;/strong&gt; constraint:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt; where T : &lt;strong&gt;class&lt;/strong&gt; 

{...}
&lt;/pre&gt;
&lt;p&gt;
    The reference/value type constraint cannot be used with base class constraint, 
    because a base class constraint implies a class. Similarly, you cannot use the 
    struct and the default constructor constraint, because a default constructor 
    constraint too implies as class. Though you can use the class and the default 
    constructor constraint, it adds no value. You can combine the reference/value 
    type constraint with an interface constraint, as long as the reference/value 
    type constraint appears first in the constraint list.
&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic5&quot;&gt;&lt;/a&gt;Generics and Casting&lt;/h2&gt;
&lt;p&gt;
    The C# compiler only lets you implicitly cast generic type parameters to Object, 
    or to constraint-specified types, as shown in &lt;strong&gt;Code block 5&lt;/strong&gt;. 
    Such implicit casting is type safe because any incompatibility is discovered at 
    compile-time.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 5. Implicit casting of generic type parameters&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;interface ISomeInterface
{...}
class BaseClass
{...}
class MyClass&amp;lt;T&amp;gt; where T : BaseClass,ISomeInterface
{
   void SomeMethod(T t)
   {
      ISomeInterface obj1 = t;
      BaseClass      obj2 = t;
      object         obj3 = t;
   }
}
&lt;/pre&gt;
&lt;p&gt;
    The compiler lets you explicitly cast generic type parameters to any other 
    interface, but not to a class:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;interface ISomeInterface
{...}
class SomeClass
{...}
class MyClass&amp;lt;T&amp;gt; 
{
   void SomeMethod(T t)
   {
      ISomeInterface obj1 = (ISomeInterface)t;//Compiles
      SomeClass      obj2 = (SomeClass)t;     //Does not compile
   }
}
&lt;/pre&gt;
&lt;p&gt;
    However, you can force a cast from a generic type parameter to any other type 
    using a temporary Object variable:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;class SomeClass
{...}

class MyClass&amp;lt;T&amp;gt; 
{
   
   void SomeMethod(T t)
   
   {
      &lt;strong&gt;object&lt;/strong&gt; temp = t;
      SomeClass obj = &lt;strong&gt;(SomeClass)&lt;/strong&gt;temp;
   
   }
}
&lt;/pre&gt;
&lt;p&gt;
    Needless to say, such explicit casting is dangerous because it may throw an 
    exception at run time if the type argument used instead of the generic type 
    parameter does not derive from the type to which you explicitly cast. Instead of 
    risking a casting exception, a better approach is to use the &lt;code class=&quot;ce&quot;&gt;is&lt;/code&gt; 
    and &lt;code class=&quot;ce&quot;&gt;as&lt;/code&gt; operators, as shown in &lt;strong&gt;Code block 6&lt;/strong&gt;. 
    The &lt;code class=&quot;ce&quot;&gt;is&lt;/code&gt; operator returns true if the generic type 
    parameter is of the queried type, and &lt;code class=&quot;ce&quot;&gt;as&lt;/code&gt; will perform a 
    cast if the types are compatible, and will return null otherwise. You can use
    &lt;code class=&quot;ce&quot;&gt;is&lt;/code&gt; and &lt;code class=&quot;ce&quot;&gt;as&lt;/code&gt; on both generic type 
    parameters and on generic classes with specific type arguments.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 6. Using &amp;#39;is&amp;#39; and &amp;#39;as&amp;#39; operators on generic type parameters&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt; 
{
   public void SomeMethod(T t)
   {
      if(t is int)
      {...} 

      if(t is LinkedList&amp;lt;int,string&amp;gt;)
      {...}

      string str = t as string;
      if(str != null)
      {...}

      LinkedList&amp;lt;int,string&amp;gt; list = t as LinkedList&amp;lt;int,string&amp;gt;;
      if(list != null)
      {...}
   }
}
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic6&quot;&gt;&lt;/a&gt;Inheritance and Generics&lt;/h2&gt;
&lt;p&gt;
    When deriving from a generic base class, you must provide a type argument 
    instead of the base-class&amp;#39;s generic type parameter:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass&amp;lt;T&amp;gt;
{...}
public class SubClass : BaseClass&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    If the subclass is generic, instead of a concrete type argument, you can use the 
    subclass generic type parameter as the specified type for the generic base 
    class:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class SubClass&lt;strong&gt;&amp;lt;T&amp;gt;&lt;/strong&gt; : BaseClass&lt;strong&gt;&amp;lt;T&amp;gt;&lt;/strong&gt; 
{...}
&lt;/pre&gt;
&lt;p&gt;
    When using the subclass generic type parameters, you must repeat any constraints 
    stipulated at the base class level at the subclass level. For example, 
    derivation constraint:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass&amp;lt;T&amp;gt;  where T : ISomeInterface 
{...}
public class SubClass&amp;lt;T&amp;gt; : BaseClass&amp;lt;T&amp;gt; where T : ISomeInterface
{...}
&lt;/pre&gt;
&lt;p&gt;
    Or constructor constraint:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass&amp;lt;T&amp;gt;  where T : new()
{   
   public T SomeMethod()
   {
      return new T();
   }
}
public class SubClass&amp;lt;T&amp;gt; : BaseClass&amp;lt;T&amp;gt; where T&lt;strong&gt; : new() &lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    A base class can define virtual methods whose signatures use generic type 
    parameters. When overriding them, the subclass must provide the corresponding 
    types in the method signatures:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass&amp;lt;T&amp;gt;
{ 
   public virtual T SomeMethod()
   {...}
}
public class SubClass: BaseClass&amp;lt;&lt;strong&gt;int&lt;/strong&gt;&amp;gt;
{ 
   public override &lt;strong&gt;int&lt;/strong&gt; SomeMethod()
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    If the subclass is generic it can also use its own generic type parameters for 
    the override:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class SubClass&amp;lt;T&amp;gt;: BaseClass&amp;lt;T&amp;gt;
{ 
   public override T SomeMethod()
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    You can define generic interfaces, generic abstract classes, and even generic 
    abstract methods. These types behave like any other generic base type:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface ISomeInterface&amp;lt;T&amp;gt;
{
   T SomeMethod(T t);
}
public abstract class BaseClass&amp;lt;T&amp;gt;
{
   public abstract T SomeMethod(T t);
}

public class SubClass&amp;lt;T&amp;gt; : BaseClass&amp;lt;T&amp;gt;
{
   public override T SomeMethod(T t) 
   {...)
}
&lt;/pre&gt;
&lt;p&gt;
    There is an interesting use for generic abstract methods and generic interfaces. 
    In C# 2.0, it is impossible to use operators such as + or += on generic type 
    parameters. For example, the following code does not compile because C# 2.0 does 
    not have operator constraints:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Calculator&amp;lt;T&amp;gt;
{
   public T Add(T arg1,T arg2)
   {
      return arg1 + arg2;//Does not compile 
   }
   //Rest of the methods 
}
&lt;/pre&gt;
&lt;p&gt;
    Nonetheless, you can compensate using abstract methods (or preferably 
    interfaces) by defining generic operations. Since an abstract method cannot have 
    any code in it, you can specify the generic operations at the base class level, 
    and provide a concrete type and implementation at the subclass level:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public abstract class BaseCalculator&amp;lt;T&amp;gt;
{
   public abstract T Add(T arg1,T arg2);
   public abstract T Subtract(T arg1,T arg2);
   public abstract T Divide(T arg1,T arg2);
   public abstract T Multiply(T arg1,T arg2);
}
public class MyCalculator : BaseCalculator&amp;lt;int&amp;gt;
{
   public override int Add(int arg1, int arg2)
   {
      return arg1 + arg2;
   }
   //Rest of the methods 
} 
&lt;/pre&gt;
&lt;p&gt;
    A generic interface will yield a somewhat cleaner solution as well:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface ICalculator&amp;lt;T&amp;gt;
{
   T Add(T arg1,T arg2);
   //Rest of the methods 
}
public class MyCalculator : ICalculator&amp;lt;int&amp;gt;
{
   public int Add(int arg1, int arg2)
   {
      return arg1 + arg2;
   }
   //Rest of the methods 
}
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic7&quot;&gt;&lt;/a&gt;Generic Methods&lt;/h2&gt;
&lt;p&gt;
    In C# 2.0, a method can define generic type parameters, specific to its 
    execution scope:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt;
{
   public void MyMethod&amp;lt;X&amp;gt;(X x)
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    This is an important capability because it allows you to call the method with a 
    different type every time, which is very handy for utility classes.
&lt;/p&gt;
&lt;p&gt;
    You can define method-specific generic type parameters even if the containing 
    class does not use generics at all:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass
{
   public void MyMethod&amp;lt;T&amp;gt;(T t)
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    This ability is for methods only. Properties or indexers can only use generic 
    type parameters defined at the scope of the class.
&lt;/p&gt;
&lt;p&gt;
    When calling a method that defines generic type parameters, you can provide the 
    type to use at the call site:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyClass obj = new MyClass();
obj.MyMethod&amp;lt;int&amp;gt;(3);
&lt;/pre&gt;
&lt;p&gt;
    That said, when the method is invoked the C# compiler is smart enough to infer 
    the correct type based on the type of parameter passed in, and it allows 
    omitting the type specification altogether:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyClass obj = new MyClass();
obj.MyMethod(3);
&lt;/pre&gt;
&lt;p&gt;
    This ability is called generic type inference. Note that the compiler cannot 
    infer the type based on the type of the returned value alone:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass
{
   public T MyMethod&amp;lt;T&amp;gt;()
   {}
}
MyClass obj = new MyClass();
int number = obj.MyMethod();//Does not compile 
&lt;/pre&gt;
&lt;p&gt;
    When a method defines its own generic type parameters, it can also define 
    constraints for these types:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass
{
   public void SomeMethod&amp;lt;T&amp;gt;(T t) where T : IComparable&amp;lt;T&amp;gt; 
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    However, you cannot provide method-level constraints for class-level generic 
    type parameters. All constraints for class-level generic type parameters must be 
    defined at the class scope.
&lt;/p&gt;
&lt;p&gt;
    When overriding a virtual method that defines generic type parameters, the 
    subclass method must redefine the method-specific generic type parameter:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass
{
   public virtual void SomeMethod&amp;lt;T&amp;gt;(T t)
   {...}
}
public class SubClass : BaseClass
{
   public override void SomeMethod&amp;lt;T&amp;gt;(T t)
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    The subclass implementation must repeat all constraints that appeared at the 
    base method level:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass
{
   public virtual void SomeMethod&amp;lt;T&amp;gt;(T t) where T : new()
   {...}
}
public class SubClass : BaseClass
{
   public override void SomeMethod&amp;lt;T&amp;gt;(T t) where T : new()
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    Note that the method override cannot define new constraints that did not appear 
    at the base method.
&lt;/p&gt;
&lt;p&gt;
    In addition, if the subclass method calls the base class implementation of the 
    virtual method, it must specify the type argument to use instead of the generic 
    base method type parameter. You can either explicitly specify it yourself or 
    rely on type inference if it is available:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class BaseClass
{ 
   public virtual void SomeMethod&amp;lt;T&amp;gt;(T t)
   {...}
}
public class SubClass : BaseClass
{
   public override void SomeMethod&amp;lt;T&amp;gt;(T t)
   {
      base.SomeMethod&amp;lt;T&amp;gt;(t);
      base.SomeMethod(t);
   }
}
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Generic Static Method&lt;/h3&gt;
&lt;p&gt;
    C# allows you to define static methods that use generic type parameters. 
    However, when invoking such a static method, you need to provide the concrete 
    type for the containing class at the call site, such as in this example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt;
{
   
   public &lt;strong&gt;static&lt;/strong&gt; T SomeMethod(T t)
   
   {...}
}
int number = MyClass&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt;.SomeMethod(3); 
&lt;/pre&gt;
&lt;p&gt;
    Static methods can define method-specific generic type parameters and 
    constraints, similar to instance methods. When calling such methods, you need to 
    provide the method-specific types at the call site, either explicitly:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt;
{
   public static T SomeMethod&amp;lt;X&amp;gt;(T t,X x)
   {..}
}
int number = MyClass&amp;lt;int&amp;gt;.SomeMethod&amp;lt;string&amp;gt;(3,&amp;quot;AAA&amp;quot;);
&lt;/pre&gt;
&lt;p&gt;
    Or rely on type inference when possible:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;int number = MyClass&amp;lt;int&amp;gt;.SomeMethod(3,&amp;quot;AAA&amp;quot;);
&lt;/pre&gt;
&lt;p&gt;
    Generic static methods are subjected to all constraints imposed on the generic 
    type parameter&lt;strong&gt; &lt;/strong&gt;they use at the class level. As with instance 
    method, you can provide constraints for generic type parameters defined by the 
    static method:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass
{
   public static T SomeMethod&amp;lt;T&amp;gt;(T t) where T : IComparable&amp;lt;T&amp;gt; 
   {...}
}
&lt;/pre&gt;
&lt;p&gt;
    Operators in C# are nothing more than static methods and C# allows you to 
    overload operators for your generic types. Imagine that the generic &lt;strong&gt;
    LinkedList&lt;/strong&gt; of &lt;strong&gt;Code block 3&lt;/strong&gt; provided the + operator for 
    concatenating linked lists. The + operator enables you to write the following 
    elegant code:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&amp;lt;int,string&amp;gt; list1 = new LinkedList&amp;lt;int,string&amp;gt;();
LinkedList&amp;lt;int,string&amp;gt; list2 = new LinkedList&amp;lt;int,string&amp;gt;();
 ...
LinkedList&amp;lt;int,string&amp;gt; list3 = list1+list2;
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 7&lt;/strong&gt; shows the implementation of the generic + operator 
    on the &lt;strong&gt;LinkedList&lt;/strong&gt; class. Note that operators cannot define new 
    generic type parameters.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 7. Implementing a generic operator&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt;
{
   public static LinkedList&amp;lt;K,T&amp;gt; operator+(LinkedList&amp;lt;K,T&amp;gt; lhs,
                                           LinkedList&amp;lt;K,T&amp;gt; rhs)
   {
      return concatenate(lhs,rhs);
   }
   static LinkedList&amp;lt;K,T&amp;gt; concatenate(LinkedList&amp;lt;K,T&amp;gt; list1,
                                      LinkedList&amp;lt;K,T&amp;gt; list2)
   {
      LinkedList&amp;lt;K,T&amp;gt; newList = new LinkedList&amp;lt;K,T&amp;gt;(); 
      Node&amp;lt;K,T&amp;gt; current;
      current = list1.m_Head;
      while(current != null)
      {
         newList.AddHead(current.Key,current.Item);
         current = current.NextNode;
      }
      current = list2.m_Head;
      while(current != null)
      {
         newList.AddHead(current.Key,current.Item);
         current = current.NextNode;
      }
      return newList;
   }
   //Rest of LinkedList
}
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic8&quot;&gt;&lt;/a&gt;Generic Delegates&lt;/h2&gt;
&lt;p&gt;
    A delegate defined in a class can take advantage of the generic type parameter&lt;strong&gt;
    &lt;/strong&gt;of that class. For example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt;
{
   public delegate void GenericDelegate(T t);
   public void SomeMethod(T t)
   {...} 
}
&lt;/pre&gt;
&lt;p&gt;
    When specifying a type for the containing class, it affects the delegate as 
    well:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyClass&amp;lt;int&amp;gt; obj = new MyClass&amp;lt;int&amp;gt;();
MyClass&amp;lt;int&amp;gt;.GenericDelegate del;

del = new MyClass&amp;lt;int&amp;gt;.GenericDelegate(obj.SomeMethod);
del(3);
&lt;/pre&gt;
&lt;p&gt;
    C# 2.0 allows you to make a direct assignment of a method reference into a 
    delegate variable:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyClass&amp;lt;int&amp;gt; obj = new MyClass&amp;lt;int&amp;gt;();
MyClass&amp;lt;int&amp;gt;.GenericDelegate del;

del = obj.SomeMethod;
&lt;/pre&gt;
&lt;p&gt;
    I am calling this feature &lt;em&gt;delegate inference&lt;/em&gt;. The compiler is capable 
    of inferring the type of the delegate you assign into, finding if the target 
    object has a method by the name you specify, and verifying that the method&amp;#39;s 
    signature matches. Then, the compiler creates a new delegate of the inferred 
    argument type (including the correct type instead of the generic type 
    parameter), and assigns the new delegate into the inferred delegate.
&lt;/p&gt;
&lt;p&gt;
    Like classes, structs, and methods, delegates can define generic type parameters 
    too:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt;
{
   public delegate void GenericDelegate&amp;lt;X&amp;gt;(T t,X x);
}
&lt;/pre&gt;
&lt;p&gt;
    Delegates defined outside the scope of a class can use generic type parameters. 
    In that case, you have to provide the type arguments for the delegate when 
    declaring and instantiating it:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public delegate void GenericDelegate&amp;lt;T&amp;gt;(T t);

public class MyClass
{
   public void SomeMethod(int number)
   {...}
}

MyClass obj = new MyClass();
GenericDelegate&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt; del; 

del = new GenericDelegate&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt;(obj.SomeMethod);
del(3);
&lt;/pre&gt;
&lt;p&gt;
    Alternatively, you can use delegate inference when assigning the delegate:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyClass obj = new MyClass();
GenericDelegate&amp;lt;int&amp;gt; del; 

del = obj.SomeMethod;
&lt;/pre&gt;
&lt;p&gt;
    And naturally, a delegate can define constraints to accompany its generic type 
    parameters:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public delegate void MyDelegate&amp;lt;T&amp;gt;(T t) &lt;strong&gt;where T : IComparable&amp;lt;T&amp;gt;&lt;/strong&gt;;
&lt;/pre&gt;
&lt;p&gt;
    The delegate-level constraints are enforced only on the using side, when 
    declaring a delegate variable and instantiating a delegate object, similar to 
    any other constraint at the scope of types or methods.
&lt;/p&gt;
&lt;p&gt;
    Generic delegates are especially useful when it comes to events. You can 
    literally define a limited set of generic delegates, distinguished only by the 
    number of the generic type parameters they require, and use these delegates for 
    all of your event handling needs. &lt;strong&gt;Code block 8&lt;/strong&gt; demonstrates the 
    use of a generic delegate and a generic event-handling method.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 8. Generic event handling&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public delegate void GenericEventHandler&amp;lt;S,A&amp;gt;(S sender,A args);
public class MyPublisher
{
   public event GenericEventHandler&amp;lt;MyPublisher,EventArgs&amp;gt; MyEvent;
   public void FireEvent()
   {
      MyEvent(this,EventArgs.Empty);
   }
}
public class MySubscriber&amp;lt;A&amp;gt; //Optional: can be a specific type
{
   public void SomeMethod(MyPublisher sender,A args)
   {...}
}
MyPublisher publisher = new MyPublisher();
MySubscriber&amp;lt;EventArgs&amp;gt; subscriber = new MySubscriber&amp;lt;EventArgs&amp;gt;();
publisher.MyEvent += subscriber.SomeMethod;
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 8&lt;/strong&gt; uses a generic delegate called &lt;strong&gt;
    GenericEventHandler&lt;/strong&gt;, which accepts a generic sender type and a generic 
    type parameter. Obviously, if you need more parameters, you can simply add more 
    generic type parameters, but I wanted to model &lt;strong&gt;GenericEventHandler&lt;/strong&gt; 
    after the non-generic .NET &lt;strong&gt;EventHandler&lt;/strong&gt;, defined as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public void delegate EventHandler(object sender,EventArgs args);
&lt;/pre&gt;
&lt;p&gt;
    Unlike &lt;strong&gt;EventHandler&lt;/strong&gt;, &lt;strong&gt;GenericEventHandler&lt;/strong&gt; is 
    type safe, as shown in &lt;strong&gt;Code block 8&lt;/strong&gt; because it accepts only 
    objects of the type &lt;strong&gt;MyPublisher&lt;/strong&gt; as senders, rather than mere 
    Object. In fact, .NET already defines a generic flavor of &lt;strong&gt;EventHandler
    &lt;/strong&gt;in the System namespace:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public void delegate EventHandler(object sender,A args) where A : EventArgs;
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic9&quot;&gt;&lt;/a&gt;Generics and Reflection&lt;/h2&gt;
&lt;p&gt;
    In .NET 2.0, reflection is extended to support generic type parameters. The type 
    Type can now represent generic types with specific type arguments (called &lt;em&gt;
    bounded types&lt;/em&gt;), or unspecified (&lt;em&gt;unbounded&lt;/em&gt;) types. As in C# 1.1, 
    you can obtain the Type of any type by using the &lt;strong&gt;typeof&lt;/strong&gt; 
    operator or by calling the &lt;strong&gt;GetType()&lt;/strong&gt; method that every type 
    supports. Regardless of the way you choose, both yield the same Type. For 
    example, in the following code sample, type1 is identical to &lt;strong&gt;type2&lt;/strong&gt;.
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&amp;lt;int,string&amp;gt; list = new LinkedList&amp;lt;int,string&amp;gt;();

Type type1 = &lt;strong&gt;typeof&lt;/strong&gt;(LinkedList&amp;lt;int,string&amp;gt;);
Type type2 = list.&lt;strong&gt;GetType&lt;/strong&gt;();
Debug.Assert(type1 == type2);
&lt;/pre&gt;
&lt;p&gt;
    Both &lt;strong&gt;typeof&lt;/strong&gt; and &lt;strong&gt;GetType()&lt;/strong&gt; can operate on 
    generic type parameters:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt; 
{
   public void SomeMethod(T t)
   {
      Type type = typeof(T);
      Debug.Assert(type == t.GetType());
   }
}&lt;/pre&gt;
&lt;p&gt;
    In addition, the &lt;strong&gt;typeof&lt;/strong&gt; operator can operate on unbounded 
    generic types. For example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyClass&amp;lt;T&amp;gt; 
{}
Type unboundedType = typeof(MyClass&lt;strong&gt;&amp;lt;&amp;gt;&lt;/strong&gt;);
Trace.WriteLine(unboundedType.ToString());
//Writes: MyClass`1[T]
&lt;/pre&gt;
&lt;p&gt;
    The number 1 being traced is the number of generic type parameters of the 
    generic type used. Note the use of the empty &lt;strong&gt;&amp;lt;&amp;gt;&lt;/strong&gt;. To operate on 
    an unbounded generic type with multiple type parameters, use a &amp;quot;&lt;strong&gt;,&lt;/strong&gt;&amp;quot; 
    in the &lt;strong&gt;&amp;lt;&amp;gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; 
{...}
Type unboundedList = typeof(LinkedList&amp;lt;&lt;strong&gt;,&lt;/strong&gt;&amp;gt;);
Trace.WriteLine(unboundedList.ToString());
//Writes: LinkedList&lt;strong&gt;`2&lt;/strong&gt;[K,T]
&lt;/pre&gt;
&lt;p&gt;
    Type has new methods and properties designed to provide reflection information 
    about the generic aspect of the type. &lt;strong&gt;Code block 9&lt;/strong&gt; shows the 
    new methods.&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 9. Type&amp;#39;s generic reflection members&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public abstract class Type : //Base types
{
   public virtual bool ContainsGenericParameters{get;}
   public virtual int GenericParameterPosition{get;}
   public virtual bool &lt;strong&gt;HasGenericArguments&lt;/strong&gt;{get;}
   public virtual bool IsGenericParameter{get;}
   public virtual bool IsGenericTypeDefinition{get;}
   public virtual Type BindGenericParameters(Type[] typeArgs);
   public virtual Type[] &lt;strong&gt;GetGenericArguments&lt;/strong&gt;();
   public virtual Type &lt;strong&gt;GetGenericTypeDefinition&lt;/strong&gt;();
   //Rest of the members
}
&lt;/pre&gt;
&lt;p&gt;
    The most useful of these new members are the &lt;strong&gt;HasGenericArguments
    &lt;/strong&gt;property and the &lt;strong&gt;GetGenericArguments ()&lt;/strong&gt; and &lt;strong&gt;
    GetGenericTypeDefinition() &lt;/strong&gt;methods. The rest of Type&amp;#39;s new members are 
    for advanced and somewhat esoteric scenarios beyond the scope of this article.
&lt;/p&gt;
&lt;p&gt;
    As its name indicates, &lt;strong&gt;HasGenericArguments &lt;/strong&gt;is set to true if 
    the type represented by the Type object uses generic type parameters. &lt;strong&gt;
    GetGenericArguments()&lt;/strong&gt; returns an array of Types corresponding to the 
    type arguments used. &lt;strong&gt;GetGenericTypeDefinition()&lt;/strong&gt; returns a Type 
    representing the generic form of the underlying type. &lt;strong&gt;Code block 10&lt;/strong&gt; 
    demonstrates using these generic-handling Type members to obtain generic 
    reflection information on the &lt;strong&gt;LinkedList&lt;/strong&gt; from &lt;strong&gt;Code 
    block 3&lt;/strong&gt;.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 10. Using Type for generic reflection&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&amp;lt;int,string&amp;gt; list = new LinkedList&amp;lt;int,string&amp;gt;();

Type boundedType = list.GetType();
Trace.WriteLine(boundedType.ToString());
//Writes: LinkedList`2[System.Int32,System.String]

Debug.Assert(boundedType.HasGenericArguments);

Type[] parameters = boundedType.GetGenericArguments();

Debug.Assert(parameters.Length == 2);
Debug.Assert(parameters[0] == typeof(int));
Debug.Assert(parameters[1] == typeof(string));

Type unboundedType = boundedType.GetGenericTypeDefinition();
Debug.Assert(unboundedType == typeof(LinkedList&amp;lt;,&amp;gt;));
Trace.WriteLine(unboundedType.ToString());
//Writes: LinkedList`2[K,T]
&lt;/pre&gt;
&lt;p&gt;
    Similar to Type, &lt;strong&gt;MethodInfo&lt;/strong&gt; and its base class &lt;strong&gt;
    MethodBase&lt;/strong&gt; have new members that reflect generic method information.
&lt;/p&gt;
&lt;p&gt;
    As in C# 1.1, you can use &lt;strong&gt;MethodInfo&lt;/strong&gt; (as well as a number of 
    other options) for late binding invocation. However, the type of the parameters 
    you pass for the late binding must match the bounded types used instead of the 
    generic type parameters (if any):
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList&amp;lt;int,string&amp;gt; list = new LinkedList&amp;lt;int,string&amp;gt;();
Type type = list.GetType();
MethodInfo methodInfo = type.GetMethod(&amp;quot;AddHead&amp;quot;);
object[] args = {1,&amp;quot;AAA&amp;quot;};
methodInfo.Invoke(list,args);
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Attributes and Generics&lt;/h3&gt;
&lt;p&gt;
    When defining an attribute, you can instruct the compiler that the attribute 
    should target generic type parameters, using the new &lt;strong&gt;GenericParameter&lt;/strong&gt; 
    value of the enum &lt;strong&gt;AttributeTargets&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;[AttributeUsage(AttributeTargets.GenericParameter)] 
public class SomeAttribute : Attribute
{...}
&lt;/pre&gt;
&lt;p&gt;
    Note that C# 2.0 does not allow you to define generic attributes.&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;//Does not compile:
public class SomeAttribute&amp;lt;T&amp;gt; : Attribute 
{...}
&lt;/pre&gt;
&lt;p&gt;
    Yet internally, an attribute class can take advantage of generics by using 
    generic types or define helper generic methods, like any other type:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class SomeAttribute : Attribute
{
   void SomeMethod&amp;lt;T&amp;gt;(T t)
   {...}
   LinkedList&amp;lt;int,string&amp;gt; m_List = new LinkedList&amp;lt;int,string&amp;gt;();
}
&lt;/pre&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic10&quot;&gt;&lt;/a&gt;Generics and the .NET Framework
&lt;/h2&gt;
&lt;p&gt;
    To conclude this article, here are how some other areas in .NET besides C# 
    itself are taking advantage of or interacting with generics.
&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    System.Array and Generics
&lt;/h3&gt;
&lt;p&gt;
    The &lt;strong&gt;System.Array&lt;/strong&gt; type is extended with many generic static 
    methods. The generic static methods are designed to automate and streamline 
    common tasks of working with arrays, such as iterating over the array and 
    performing an action on each element, scanning the array looking for a value 
    that matches a certain criteria (a predicate), converting and sorting the array, 
    and so on.&lt;strong&gt; Code Block 11&lt;/strong&gt; is a partial listing of these static 
    methods.&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 11. The generic methods of System.Array &lt;/strong&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public abstract class Array
{
   //Partial listing of the static methods:  
   public static IList&amp;lt;T&amp;gt; AsReadOnly&amp;lt;T&amp;gt;(T[] array);
   public static int BinarySearch&amp;lt;T&amp;gt;(T[] array, T value);
   public static int BinarySearch&amp;lt;T&amp;gt;(T[] array, T value,
                                     IComparer&amp;lt;T&amp;gt; comparer);
   public static U[] ConvertAll&amp;lt;T,U&amp;gt;(T[] array, 
                                Converter&amp;lt;T,U&amp;gt; converter);
   public static bool Exists&amp;lt;T&amp;gt;(T[] array,Predicate&amp;lt;T&amp;gt; match);
   public static T Find&amp;lt;T&amp;gt;(T[] array,Predicate&amp;lt;T&amp;gt; match);
   public static T[] FindAll&amp;lt;T&amp;gt;(T[] array, Predicate&amp;lt;T&amp;gt; match);
   public static int FindIndex&amp;lt;T&amp;gt;(T[] array, Predicate&amp;lt;T&amp;gt; match);
   public static void ForEach&amp;lt;T&amp;gt;(T[] array, Action&amp;lt;T&amp;gt; action);
   public static int  IndexOf&amp;lt;T&amp;gt;(T[] array, T value);
   public static void Sort&amp;lt;K,V&amp;gt;(K[] keys, V[] items,
                                IComparer&amp;lt;K&amp;gt; comparer);
   public static void Sort&amp;lt;T&amp;gt;(T[] array,Comparison&amp;lt;T&amp;gt; comparison) 
}
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;System.Array&lt;/strong&gt;&amp;#39;s static generic methods all work with the 
    following four generic delegates defined in the &lt;strong&gt;System&lt;/strong&gt; 
    namespace:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public delegate void Action&amp;lt;T&amp;gt;(T t);
public delegate int Comparison&amp;lt;T&amp;gt;(T x, T y);
public delegate U Converter&amp;lt;T, U&amp;gt;(T from);
public delegate bool Predicate&amp;lt;T&amp;gt;(T t);
&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 12 &lt;/strong&gt;demonstrates using these generic methods and 
    delegates. It initializes an array with all the integers from 1 to 20. Then, 
    using an anonymous method and the &lt;strong&gt;Action&amp;lt;T&amp;gt;&lt;/strong&gt; delegate, the code 
    traces these numbers using the &lt;strong&gt;Array.ForEach()&lt;/strong&gt; method. Using a 
    second anonymous method and the &lt;strong&gt;Predicate&amp;lt;T&amp;gt;&lt;/strong&gt; delegate, the code 
    finds all the prime numbers in the array by calling the &lt;strong&gt;Array.FindAll()&lt;/strong&gt; 
    method, which returns another array of the same generic type. Finally, the prime 
    numbers are traced using the same &lt;strong&gt;Action&amp;lt;T&amp;gt;&lt;/strong&gt; delegate and 
    anonymous method. Note the use of type parameter inference in &lt;strong&gt;Code block 
    12. &lt;/strong&gt;You can use the static methods without specifying the type 
    parameters.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 12. Using the generic methods of System.Array &lt;/strong&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
Action&amp;lt;int&amp;gt; trace =  delegate(int number)
                     {
                        Trace.WriteLine(number);
                     };
Predicate&amp;lt;int&amp;gt; isPrime =   delegate(int number)
                           {
                              switch(number)
                              {
                                case 1:case 2:case 3:case 5:case 7:                                 
                                case 11:case 13:case 17:case 19:
                                    return true;
                                 default:
                                    return false;
                              }
                           };
Array.&lt;strong&gt;ForEach&lt;/strong&gt;(numbers,trace);
int[] primes = Array.&lt;strong&gt;FindAll&lt;/strong&gt;(numbers,isPrime);
Array.&lt;strong&gt;ForEach&lt;/strong&gt;(primes,trace);
&lt;/pre&gt;
&lt;p&gt;
    Similar generic methods are also available on the class &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt; 
    defined in the &lt;strong&gt;System.Collections.Generic&lt;/strong&gt; namespace. These 
    methods use the same four generic delegates. In fact, you can take advantage of 
    those delegates in your code too, as shown in the following section.&lt;/p&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    The Static Collection Class&lt;/h3&gt;
&lt;p&gt;
    While both &lt;strong&gt;System.Array&lt;/strong&gt; and &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt; offer 
    handy utility methods that greatly simplify working with them, .NET does not 
    offer such support for other collections. To compensate, the source code 
    available with this article includes the static helper class &lt;strong&gt;Collection&lt;/strong&gt;, 
    defined as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public static class Collection
{
   public static IList&amp;lt;T&amp;gt; AsReadOnly&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection);
   public static U[] ConvertAll&amp;lt;T,U&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,
                                     Converter&amp;lt;T,U&amp;gt; converter);
   public static bool Contains&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,T item) 
                                               where T : IComparable&amp;lt;T&amp;gt;;
   public static bool Exists&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,Predicate&amp;lt;T&amp;gt;); 
   public static T Find&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,Predicate&amp;lt;T&amp;gt; match);
   public static T[] FindAll&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,
                                Predicate&amp;lt;T&amp;gt; match);
   public static int FindIndex&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,T value) 
                                                where T : IComparable&amp;lt;T&amp;gt;;
   public static T FindLast&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,
                               Predicate&amp;lt;T&amp;gt; match);
   public static int FindLastIndex&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,T value) 
                                                where T : IComparable&amp;lt;T&amp;gt;;
   public static void ForEach&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,Action&amp;lt;T&amp;gt; action);
   public static T[] Reverse&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection);
   public static T[] Sort&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection);
   public static T[] ToArray&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection);
   public static bool TrueForAll&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; collection,
                                    Predicate&amp;lt;T&amp;gt; match);
   //Overloaded versions for IEnumerator&amp;lt;T&amp;gt; 
}
&lt;/pre&gt;
&lt;p&gt;
    The implementation of &lt;strong&gt;Collection&lt;/strong&gt; is straightforward. For 
    example, here is the &lt;strong&gt;ForEach&amp;lt;T&amp;gt;()&lt;/strong&gt; method:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public static void ForEach&amp;lt;T&amp;gt;(IEnumerator&amp;lt;T&amp;gt; iterator,Action&amp;lt;T&amp;gt; action)
{
   /* Some parameter checking here, then: */
   while(iterator.MoveNext())
   {
      action(iterator.Current);
   }
}
&lt;/pre&gt;
&lt;p&gt;
    The &lt;strong&gt;Collection&lt;/strong&gt; static class is used very similar to both
    &lt;strong&gt;Array&lt;/strong&gt; and &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt;, utilizing the same generic 
    delegates. You can use &lt;strong&gt;Collection&lt;/strong&gt; with any collection, as long 
    as that collection supports either &lt;strong&gt;IEnumerable&lt;/strong&gt; or &lt;strong&gt;
    IEnumerator&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Queue&amp;lt;int&amp;gt; queue = new Queue&amp;lt;int&amp;gt;();
//Some code to initialize queue
Action&amp;lt;int&amp;gt; trace =  delegate(int number)
                     {
                        Trace.WriteLine(number);
                     };
Collection.ForEach(queue,trace);
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Generic Collections&lt;/h3&gt;
&lt;p&gt;
    The data structures in System.Collections are all Object-based, and thus 
    inheriting the two problems described at the beginning of this article, namely, 
    inferior performance and lack of type safety. .NET 2.0 introduces a set of 
    generic collections in the System.Collections.Generic namespace. For example, 
    there are generic &lt;strong&gt;Stack&amp;lt;T&amp;gt;&lt;/strong&gt; and a generic &lt;strong&gt;Queue&amp;lt;T&amp;gt;&lt;/strong&gt; 
    classes. The &lt;strong&gt;Dictionary&amp;lt;K,T&amp;gt;&lt;/strong&gt; data structure is equivalent to 
    the non-generic &lt;strong&gt;HashTable&lt;/strong&gt;, and there is also a &lt;strong&gt;
    SortedDictionary&amp;lt;K,T&amp;gt;&lt;/strong&gt; class somewhat like &lt;strong&gt;SortedList&lt;/strong&gt;. 
    The class &lt;strong&gt;List&amp;lt;T&amp;gt;&lt;/strong&gt; is analogous to the non-generic &lt;strong&gt;
    ArrayList&lt;/strong&gt;. Table 1 maps the main types of System.Collections.Generic to 
    those of System.Collections.
&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Table 1. Mapping System.Collections.Generic to System.Collections&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;tablediv&quot;&gt;
    &lt;table class=&quot;dtTABLE&quot;&gt;
        &lt;tr&gt;
            &lt;th&gt;
                System.Collections.Generic&lt;/th&gt;
            &lt;th&gt;
                System.Collections&lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                Comparer&amp;lt;T&amp;gt;&lt;/td&gt;
            &lt;td&gt;
                Comparer&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                Dictionary&amp;lt;K,T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                HashTable&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                LinkedList&amp;lt;T&amp;gt;&lt;/td&gt;
            &lt;td&gt;
                -&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                List&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                ArrayList&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                Queue&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                Queue&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                SortedDictionary&amp;lt;K,T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                SortedList&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                Stack&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                Stack&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                ICollection&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                ICollection&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                IComparable&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                System.IComparable&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                IDictionary&amp;lt;K,T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                IDictionary
            &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                IEnumerable&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                IEnumerable&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                IEnumerator&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                IEnumerator&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;
                IList&amp;lt;T&amp;gt;
            &lt;/td&gt;
            &lt;td&gt;
                IList&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;
    All the generic collections in System.Collections.Generic also implement the 
    generic &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; interface, defined as:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface IEnumerable&amp;lt;T&amp;gt;
{
   IEnumerator&amp;lt;T&amp;gt;&lt;strong&gt; &lt;/strong&gt;GetEnumerator();
} 
public interface IEnumerator&amp;lt;T&amp;gt; : IDisposable
{
   T Current{get;}
   bool MoveNext();
}
      
&lt;/pre&gt;
&lt;p&gt;
    Briefly, &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; provides access to the &lt;strong&gt;
    IEnumerator&amp;lt;T&amp;gt;&lt;/strong&gt; iterator interface, used for abstracted iterations over 
    the collection. All the collections implement &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt; &lt;/strong&gt;on 
    a nested struct, where the generic type parameter T is the type the collection 
    stores.
&lt;/p&gt;
&lt;p&gt;
    Of particular interest is the way the dictionary collections define their 
    iterators. A dictionary is actually a collection of not one but two types of 
    generic parameter—the key and the value. System.Collection.Generic provides a 
    generic struct called KeyValuePair&amp;lt;K,V&amp;gt; defined as:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;struct KeyValuePair&amp;lt;K,V&amp;gt;
{
   public KeyValuePair(K key,V value);
   public K Key(get;set;)
   public V Value(get;set;)
}
&lt;/pre&gt;
&lt;p&gt;
    KeyValuePair&amp;lt;K,V&amp;gt; simply stores a pair of a generic key and a generic value. 
    This struct is what the dictionary manages as a collection, and what it uses for 
    its implementation of &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt;. The &lt;strong&gt;Dictionary&lt;/strong&gt; 
    class specifies the generic KeyValuePair&amp;lt;K,V&amp;gt; structure as the item argument for
    &lt;strong&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/strong&gt; and &lt;strong&gt;ICollection&amp;lt;T&amp;gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class Dictionary&amp;lt;K,T&amp;gt; : IEnumerable&amp;lt;KeyValuePair&amp;lt;K,T&amp;gt;&amp;gt;, 
                               ICollection&amp;lt;KeyValuePair&amp;lt;K,T&amp;gt;&amp;gt;, 
                               //More interfaces
{...} 
&lt;/pre&gt;
&lt;p&gt;
    The key and value type parameters used in KeyValuePair&amp;lt;K,V&amp;gt; are of course the 
    dictionary&amp;#39;s own generic key and value type parameters. You can certainly do the 
    same in your own generic data structures that use pairs of keys and values. For 
    example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class LinkedList&amp;lt;K,T&amp;gt; : IEnumerable&amp;lt;KeyValuePair&amp;lt;K,T&amp;gt;&amp;gt; where K : IComparable&amp;lt;K&amp;gt;
{...} 
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Serialization and Generics&lt;/h3&gt;
&lt;p&gt;
    .NET allows you to have serializable generic types:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;[Serializable]
public class MyClass&lt;strong&gt;&amp;lt;T&amp;gt;&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    When serializing a type, besides the state of the object members, .NET persists 
    metadata about the object and its type. If the serializable type is generic and 
    it contains bounded types, the metadata about the generic type contains type 
    information about the bounded types as well. Consequently, each permutation of a 
    generic type with a specific argument type is considered a unique type. For 
    example, you cannot serialize an object type &lt;strong&gt;MyClass&amp;lt;int&amp;gt;&lt;/strong&gt; but 
    deserialize it into an object of type &lt;strong&gt;MyClass&amp;lt;string&amp;gt;&lt;/strong&gt;. 
    Serializing an instance of a generic type is no different from serializing a 
    non-generic type. However, when deserializing that type, you need to declare a 
    variable with matching specific types, and specify these types again when down 
    casting the Object returned from Deserialize. &lt;strong&gt;Code block 13&lt;/strong&gt; 
    shows serialization and deserialization of a generic type.&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 13. Client-side serialization of a generic type&lt;/strong&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;[Serializable]
public class MyClass&amp;lt;T&amp;gt;
{...}
MyClass&amp;lt;int&amp;gt; obj1 = new MyClass&amp;lt;int&amp;gt;();

IFormatter formatter = new BinaryFormatter();&amp;nbsp;
Stream stream = new FileStream(&amp;quot;obj.bin&amp;quot;,FileMode.Create,FileAccess.ReadWrite); 
using(stream)
{
   formatter.Serialize(stream,obj1);
   stream.Seek(0,SeekOrigin.Begin);

   MyClass&amp;lt;int&amp;gt; obj2; 
   obj2 = (MyClass&amp;lt;int&amp;gt;)formatter.Deserialize(stream);
}&lt;/pre&gt;
&lt;p&gt;
    Note that &lt;strong&gt;IFormatter&lt;/strong&gt; is object-based. You can compensate by 
    defining a generic version of &lt;strong&gt;IFormatter&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public interface IGenericFormatter
{
   T Deserialize&amp;lt;T&amp;gt;(Stream serializationStream);
   void Serialize&amp;lt;T&amp;gt;(Stream serializationStream,T graph);
}
&lt;/pre&gt;
&lt;p&gt;
    You can implement &lt;strong&gt;IGenericFormatter&lt;/strong&gt; by containing an-object 
    based formatter:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class GenericFormatter&amp;lt;F&amp;gt; : IGenericFormatter 
                                   where F : IFormatter,new()
{
   IFormatter m_Formatter = new F();
   public T Deserialize&amp;lt;T&amp;gt;(Stream serializationStream)
   {
      return (T)m_Formatter.Deserialize(serializationStream);
   }
   public void Serialize&amp;lt;T&amp;gt;(Stream serializationStream,T graph)
   {
      m_Formatter.Serialize(serializationStream,graph);
   }
}
&lt;/pre&gt;
&lt;p&gt;
    Note the use of the two constraints on the generic type parameter F. While it is 
    possible to use &lt;strong&gt;GenericFormatter&amp;lt;F&amp;gt;&lt;/strong&gt; as-is:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;   
using GenericBinaryFormatter = GenericFormatter&amp;lt;BinaryFormatter&amp;gt;;
using GenericSoapFormatter2  = GenericFormatter&amp;lt;SoapFormatter&amp;gt;;
&lt;/pre&gt;
&lt;p&gt;
    You can also strongly-type the formatter to use:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public sealed class GenericBinaryFormatter : GenericFormatter&amp;lt;BinaryFormatter&amp;gt;
{}
public sealed class GenericSoapFormatter : GenericFormatter&amp;lt;SoapFormatter&amp;gt;
{}
&lt;/pre&gt;
&lt;p&gt;
    The advantage of a strongly-typed definition is that you can share it across 
    files and assemblies, as opposed to the &lt;strong&gt;using&lt;/strong&gt; alias.
&lt;/p&gt;
&lt;p&gt;
    &lt;strong&gt;Code block 14&lt;/strong&gt; is the same as &lt;strong&gt;Code block 13&lt;/strong&gt; 
    expect it uses the generic formatter:&lt;/p&gt;
&lt;p class=&quot;label&quot;&gt;
    &lt;strong&gt;Code block 14. Using IGenericFormatter &lt;/strong&gt;
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;[Serializable]
public class MyClass&amp;lt;T&amp;gt;
{...}
MyClass&amp;lt;int&amp;gt; obj1 = new MyClass&amp;lt;int&amp;gt;();

IGenericFormatter formatter = new GenericBinaryFormatter();&amp;nbsp;
Stream stream = new FileStream(&amp;quot;obj.bin&amp;quot;,FileMode.Create,FileAccess.ReadWrite); 
using(stream)
{
   formatter.Serialize(stream,obj1);
   stream.Seek(0,SeekOrigin.Begin);
   MyClass&amp;lt;int&amp;gt; obj2; 
   obj2 = formatter.Deserialize(stream);
}
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    Generics and Remoting&lt;/h3&gt;
&lt;p&gt;
    You can define and deploy remote classes that utilize generics, and you can use 
    programmatic or administrative configuration. Consider the class &lt;strong&gt;
    MyServer&amp;lt;T&amp;gt;&lt;/strong&gt; that uses generics and is derived from &lt;strong&gt;
    MarshalByRefObject&lt;/strong&gt;:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyServer&amp;lt;T&amp;gt; : MarshalByRefObject
{...}
&lt;/pre&gt;
&lt;p&gt;
    You can only access this class over remoting when the type parameter &lt;strong&gt;T
    &lt;/strong&gt;is a marshalable object. This implies that &lt;strong&gt;T &lt;/strong&gt;is either 
    a serializable type or is derived from &lt;strong&gt;MarshalByRefObject&lt;/strong&gt;. You 
    can enforce that by constraining &lt;strong&gt;T &lt;/strong&gt;to derive from &lt;strong&gt;
    MarshalByRefObject&lt;/strong&gt;:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;public class MyServer&amp;lt;T&amp;gt; : MarshalByRefObject 
                           &lt;strong&gt;where T : MarshalByRefObject&lt;/strong&gt;
{...}
&lt;/pre&gt;
&lt;p&gt;
    When using administrative type registration, you need to specify the exact type 
    arguments to use instead of the generic type parameters. You must name the types 
    in a language-neutral manner, and provide fully qualified namespaces. For 
    example, suppose the class &lt;strong&gt;MyServer&amp;lt;T&amp;gt;&lt;/strong&gt; is defined in the 
    namespace &lt;strong&gt;RemoteServer&lt;/strong&gt; in the assembly &lt;strong&gt;ServerAssembly&lt;/strong&gt;, 
    and you want to use it with integer instead of the generic type parameter T, in 
    client activated mode. In that case, the required client-side type registration 
    entry in the configuration file would be:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&amp;lt;client url=&amp;quot;...some url goes here...&amp;quot;&amp;gt; 
   &amp;lt;activated type=&amp;quot;RemoteServer.MyServer&lt;strong&gt;[[System.Int32]]&lt;/strong&gt;,ServerAssembly&amp;quot;/&amp;gt;
&amp;lt;/client&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
    The matching host-side type registration entry in the configuration file is:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&amp;lt;service&amp;gt; 
   &amp;lt;activated type=&amp;quot;RemoteServer.MyServer&lt;strong&gt;[[System.Int32]]&lt;/strong&gt;,ServerAssembly&amp;quot;/&amp;gt; 
&amp;lt;/service&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
    The double square brackets are used to specify multiple types. For example:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;LinkedList[[System.Int32],[System.String]]
&lt;/pre&gt;
&lt;p&gt;
    When using programmatic configuration, you configure activation modes and type 
    registration similar to C# 1.1, except when defining the type of the remote 
    object you have to provide type arguments instead of the generic type 
    parameters. For example, for host-side activation mode and type registration you 
    would write:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Type serverType = typeof(MyServer&amp;lt;int&amp;gt;);
RemotingConfiguration.RegisterActivatedServiceType(serverType);
&lt;/pre&gt;
&lt;p&gt;
    For client-side type activation mode and location registration, you have the 
    following:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Type serverType = typeof(MyServer&amp;lt;int&amp;gt;);      
string url = ...; //some url initialization 
RemotingConfiguration.RegisterWellKnownClientType(serverType,url);
&lt;/pre&gt;
&lt;p&gt;
    When instantiating the remote server, simply provide the type arguments, just as 
    if you where using a local generic type:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;MyServer&amp;lt;int&amp;gt; obj;
obj = new MyServer&amp;lt;int&amp;gt;();
//Use obj
&lt;/pre&gt;
&lt;p&gt;
    Instead of using new, the client can optionally use the methods of the &lt;strong&gt;
    Activator&lt;/strong&gt; class to connect to remote objects. When using &lt;strong&gt;
    Activator.GetObject()&lt;/strong&gt; you need to provide the type arguments to use, 
    and provide the argument types when explicitly casting the returned Object:
&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;string url = ...; //some url initialization 
Type serverType = typeof(MyServer&amp;lt;int&amp;gt;);
MyServer&amp;lt;int&amp;gt; obj;
obj = (MyServer&amp;lt;int&amp;gt;)Activator.GetObject(serverType,url);
//Use obj
&lt;/pre&gt;
&lt;p&gt;
    You can also use &lt;strong&gt;Activator.CreateInstance()&lt;/strong&gt; with generic types:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Type serverType = typeof(MyServer&amp;lt;int&amp;gt;);
MyServer&amp;lt;int&amp;gt; obj;
obj = (MyServer&amp;lt;int&amp;gt;)Activator.CreateInstance(serverType);
//Use obj
&lt;/pre&gt;
&lt;p&gt;
    In fact, &lt;strong&gt;Activator&lt;/strong&gt; also offers a generic version of &lt;strong&gt;
    CreateInstance()&lt;/strong&gt;, defined as:&lt;/p&gt;
&lt;p&gt;
    &lt;code&gt;T CreateInstance&amp;lt;T&amp;gt;();&lt;/code&gt;&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;/pre&gt;
&lt;p&gt;
    &lt;strong&gt;CreateInstance&amp;lt;T&amp;gt;()&lt;/strong&gt; is used similar to the non-generic flavor, 
    only with the added benefit of type safety:&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;Type serverType = typeof(MyServer&amp;lt;int&amp;gt;);
MyServer&amp;lt;int&amp;gt; obj;
obj = Activator.CreateInstance(serverType);
//Use obj
&lt;/pre&gt;
&lt;h3 class=&quot;dtH1&quot;&gt;
    What Generics Cannot Do&lt;/h3&gt;
&lt;p&gt;
    Under .NET 2.0, you cannot define generic Web services. That is, Web methods 
    that use generic type parameters. The reason is that none of the Web service 
    standards support generic services.
&lt;/p&gt;
&lt;p&gt;
    You also cannot use generic types on a serviced component. The reason is that 
    generics do not meet COM visibility requirements, which are required for 
    serviced components (just like you could not use C++ templates in COM or COM+).
&lt;/p&gt;
&lt;h2 class=&quot;dtH1&quot;&gt;
    &lt;a id=&quot;csharp_generics_topic11&quot;&gt;&lt;/a&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
    C# generics are an invaluable part of your development arsenal. They improve 
    performance, type safety and quality, reduce repetitive programming tasks, 
    simplify the overall programming model, and do so with elegant, readable syntax. 
    While the roots of C# generics are C++ templates, C# takes generics to a new 
    level by providing compile-time safety and support. C# utilizes two-phase 
    compilation, metadata, and innovative concepts such as constraints and generic 
    methods. No doubt future versions of C# will continue to evolve generics, adding 
    new capabilities and extending generics to other areas of .NET Framework such as 
    data access or localization.
&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://sanjaylegha.blogspot.com/feeds/7916832202021405154/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/introduction-to-c-generics.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/7916832202021405154'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3977111882153719926/posts/default/7916832202021405154'/><link rel='alternate' type='text/html' href='http://sanjaylegha.blogspot.com/2012/02/introduction-to-c-generics.html' title='Introduction to C# Generics (MSDN)'/><author><name>Sanjay Legha</name><uri>http://www.blogger.com/profile/07248476127183286127</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry></feed>