<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Software Rockstar &#187; Generics</title>
	<atom:link href="http://www.softwarerockstar.com/tag/generics/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.softwarerockstar.com</link>
	<description>Coaching and mentoring on a journey from a Developer to an IT Leader</description>
	<lastBuildDate>Tue, 13 Sep 2011 17:18:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Finding Distinct Elements In A List(T)</title>
		<link>http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/</link>
		<comments>http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 05:26:44 +0000</pubDate>
		<dc:creator>SoftwareRockstar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[complex solutions]]></category>
		<category><![CDATA[Customer]]></category>
		<category><![CDATA[customer class]]></category>
		<category><![CDATA[distinct elements]]></category>
		<category><![CDATA[element]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[public string]]></category>
		<category><![CDATA[target class]]></category>
		<category><![CDATA[var]]></category>

		<guid isPermaLink="false">http://www.softwarerockstar.com/?p=676</guid>
		<description><![CDATA[LINQ provides a Distinct() method, but in order to find distinct elements in a list of some target class, we must first implement the IEqualityComparer&#60;T&#62; interface in our target class. That&#8217;s what Distinct() uses in order to compute whether one element is the same as another element. Implementing IEqualityComparer&#60;T&#62;, however, is not so straightforward as [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ provides a <a target="_blank" href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx">Distinct()</a> method, but in order to find distinct elements in a list of some target class, we must first implement the <a target="_blank" href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer&lt;T&gt;</a> interface in our target class.  That&#8217;s what <a target="_blank" href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx">Distinct()</a> uses in order to compute whether one element is the same as another element.  Implementing <a target="_blank" href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer&lt;T&gt;</a>, however, is not so straightforward as it requires us to override <a href="http://www.google.com/url?sa=t&#038;source=web&#038;cd=2&#038;ved=0CB0QFjAB&#038;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2F336aedhh(v%3Dvs.71).aspx&#038;ei=rio6Tp61MYGctweksqHcAg&#038;usg=AFQjCNH13w_CEJs7V6csZi9f2VJ4rugHNw&#038;sig2=JR4gaX00_PrNLXBGLXMSBQ" target="_blank">Equals()</a> and <a href="http://www.google.com/url?sa=t&#038;source=web&#038;cd=1&#038;sqi=2&#038;ved=0CBUQFjAA&#038;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fsystem.object.gethashcode.aspx&#038;ei=4Co6Tp3nFNK4tgfcvvXNDg&#038;usg=AFQjCNFXwuFFRvlbt2CLiNF7wqUWphx10g&#038;sig2=KGBDmnWpJpP512ndK2zAIQ" target="_blank">GetHashCode()</a> methods.  Most of the times if all we need to do is just to find non-duplicated elements in a given list, IEqualityComparer&lt;T&gt; route seems like an overkill.<span id="more-676"></span></p>
<p>Other developers have come up with some slick ways to solve this problem like <a target="_blank" href="http://www.codeproject.com/KB/linq/GenericPropertyComparer.aspx">creating a generic EqualityComparer&lt;T&gt;</a> and <a target="_blank" href="http://johnnycoder.com/blog/2009/12/22/c-hashsett/">using HashSet&lt;T&gt;</a>, but I find both of those methods to be more complex solutions to a simpler problem.</p>
<p>I usually use a much simpler way to accomplish the same task which I will share with you below.  Consider the following rather simple Customer class:</p>
<pre class="brush: csharp">
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</pre>
<p>We initialize this class with some customers as follows:</p>
<pre class="brush: csharp">
List&lt; Customer &gt; customers = new List&lt; Customer &gt;;
{
    new Customer {FirstName = &quot;John&quot;, LastName = &quot;Doe&quot;},
    new Customer {FirstName = &quot;Jane&quot;, LastName = &quot;Doe&quot;},
    new Customer {FirstName = &quot;John&quot;, LastName = &quot;Doe&quot;},
    new Customer {FirstName = &quot;Jay&quot;, LastName = null},
    new Customer {FirstName = &quot;Jay&quot;, LastName = &quot;Doe&quot;}
};
</pre>
<p>So far so good!  Now all we need is a list of distinct elements by, let&#8217;s say, FirstName (find all elements that have different first names).  We can do that by first grouping our list by FirstName, and then selecting only the first element out of each group as follows:</p>
<pre class="brush: csharp">
var distinctCustomers = customers.GroupBy(s =&gt; s.FirstName)
    .Select(s =&gt; s.First());

// Will print John Doe, Jane Doe, and Jay
foreach(var customer in distinctCustomers)
    Console.WriteLine(&quot;{0} {1}&quot;, customer.FirstName, customer.LastName);
</pre>
<p>Easy enough?  Now let&#8217;s say we need to find out whether or not the list actually contains any duplicates to begin with.  We can also do that easily by again grouping and then computing whether or not any of the groups contain more than 1 elements as follows:</p>
<pre class="brush: csharp">
var hasDusplicates = customers.GroupBy(s =&gt; s.FirstName)
    .Any(s =&gt; s.Count() &gt; 1);

Console.WriteLine(hasDusplicates);
</pre>
<p>I hope that this simplifies your code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.softwarerockstar.com/2011/08/finding-distinct-elements-in-a-listt/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using IXmlSerializable To Overcome &#8220;not expected&#8221; Error On Derived Classes</title>
		<link>http://www.softwarerockstar.com/2006/12/using-ixmlserializable-to-overcome-not-expected-error-on-derived-classes/</link>
		<comments>http://www.softwarerockstar.com/2006/12/using-ixmlserializable-to-overcome-not-expected-error-on-derived-classes/#comments</comments>
		<pubDate>Sun, 10 Dec 2006 18:50:00 +0000</pubDate>
		<dc:creator>SoftwareRockstar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[compilation time]]></category>
		<category><![CDATA[concrete type]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[grunt work]]></category>
		<category><![CDATA[ingenious solutions]]></category>
		<category><![CDATA[IXmlSerializable]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[region]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[xml serialization]]></category>
		<category><![CDATA[XmlSerializer]]></category>

		<guid isPermaLink="false">http://mharoon.wordpress.com/2006/12/10/using-ixmlserializable-to-overcome-not-expected-error-on-derived-classes/</guid>
		<description><![CDATA[This article extends upon Simon Hewitt&#8217;s article on CodeProject. It is strongly recommended that you read Simon&#8217;s article also in order to fully understand the concepts. BACKGROUND XML serialization is an indispensable technique that has built-in support for in the .NET Framework. Using XML serialization, objects can be serialized to XML streams that may be [...]]]></description>
			<content:encoded><![CDATA[<p>This article extends upon <a href="http://www.codeproject.com/csharp/xmlserializerforunknown.asp">Simon Hewitt&#8217;s article on CodeProject</a>. It is strongly recommended that you read Simon&#8217;s article also in order to fully understand the concepts.</p>
<p><strong>BACKGROUND</strong><br />
XML serialization is an indispensable technique that has built-in support for in the .NET Framework. Using XML serialization, objects can be serialized to XML streams that may be persisted to permanent storage such as files, as well as XML streams can be converted back to objects with exactly the same state as at the time of serialization. With .NET Framework&#8217;s built-in support for XML serialization, all this can be achieved with only a few lines of code using the <a href="http://msdn2.microsoft.com/en-us/system.xml.serialization.xmlserializer.aspx">System.Xml.Serialization.XmlSerializer</a> object.</p>
<p><strong>PROBLEM</strong><br />
The problem with <a href="http://msdn2.microsoft.com/en-us/system.xml.serialization.xmlserializer.aspx">XmlSerializer</a> is, however, that it works by generating an on-the-fly assembly behind the scenes at compilation time, that has logic for serialization and deserialization of a given type. For this reason, the exact (concrete) type of the object and it&#8217;s public properties must be known to the compiler at the time of compilation. If we try to serialize an object that, for example, has a public member of a given base type, then at run-time we receive a <a href="http://msdn2.microsoft.com/en-us/system.invalidoperationexception.aspx">System.InvalidOperationException</a> if the public member was set to a derived type.</p>
<p><strong>WORKAROUND</strong><br />
The workaround to above problem has generally been resorting to custom XML serialization, which can get pretty complicated at times.</p>
<p><strong>SOLUTION</strong><br />
An ingenious solutions was discovered by <a href="http://www.codeproject.com/csharp/xmlserializerforunknown.asp">Simon Hewitt</a> using the <a href="http://msdn2.microsoft.com/en-us/system.xml.serialization.ixmlserializable.aspx">System.Xml.Serialization.IXmlSerializable</a> interface that allows us to mitigate the by-design issue of XmlSerializer object. While this solution works very well, it requires that a new class be created for each base class that we need serialization support for.</p>
<p>Using C# generics, I took the liberty of extending Simon&#8217;s solution, eliminating the need for such new classes, and encapsulating the grunt work into just one class. Once this class has been added to our project (our referenced from another assembly), all we really need to do is decorate any of our public members of base type (that may be substituted with derived types at runtime) with an attribute.</p>
<pre class="brush: csharp">
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace Vocalsoft.Xml.Serialization
{
public class CustomSerializer : IXmlSerializable
{
#region Private Members
///
/// Holds the object that this serializer operates on.
///
private ItemType _parameters;
#endregion

#region Static Methods
///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
CustomSerializer(ItemType p)
{
return p == null ? null : new CustomSerializer(p);
}

///
/// Implicit operators the specified p.
///
/// The p.
///
public static implicit operator
ItemType(CustomSerializer p)
{
return p.Equals(default(ItemType)) ? default(ItemType) : p.Parameters;
}
#endregion Static

#region Constructors
///
/// Initializes a new instance of the &quot;/&gt; class.
///
public CustomSerializer()
{
}

///
/// Initializes a new instance of the &quot;/&gt; class.
///
/// The parameters.
public CustomSerializer(ItemType parameters)
{
this._parameters = parameters;
}
#endregion Constructors

#region Properties

///
/// Gets parameters.
///
/// The parameters.
public ItemType Parameters
{
get { return _parameters; }
}

#endregion Properties

#region IXmlSerializable Implementation

///
/// Returns schema of the XML document representation of the object that is produced by the method and consumed by the method.
///
///
/// An that describes the XML representation of the object that is produced by the method and consumed by the method.
///
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}

///
/// Generates an object from its XML representation.
///
/// The stream from which the object is deserialized.
void IXmlSerializable.ReadXml(XmlReader reader)
{
// Get type from xml attribute
Type type = Type.GetType(reader.GetAttribute(&quot;type&quot;));

// Deserialize
reader.ReadStartElement();
this._parameters = (ItemType)new XmlSerializer(type).Deserialize(reader);
reader.ReadEndElement();
}

///
/// Converts an object into its XML representation.
///
/// The stream to which the object is serialized.
void IXmlSerializable.WriteXml(XmlWriter writer)
{
// Write type as xml attribute
writer.WriteAttributeString(&quot;type&quot;, _parameters.GetType().ToString());
new XmlSerializer(_parameters.GetType()).Serialize(writer, _parameters);
}

#endregion IXmlSerializable Implementation

}
}
</pre>
<p>Once the above class has been added to our project, all we need to do is add an attribute directly on the base class property as follows:</p>
<pre class="brush: csharp">
[XmlElement(Type = typeof(CustomSerializer))]
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.softwarerockstar.com/2006/12/using-ixmlserializable-to-overcome-not-expected-error-on-derived-classes/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Array vs. ArrayList</title>
		<link>http://www.softwarerockstar.com/2006/10/array-vs-arraylist/</link>
		<comments>http://www.softwarerockstar.com/2006/10/array-vs-arraylist/#comments</comments>
		<pubDate>Mon, 16 Oct 2006 13:20:00 +0000</pubDate>
		<dc:creator>SoftwareRockstar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Generics]]></category>

		<guid isPermaLink="false">http://mharoon.wordpress.com/2006/10/16/array-vs-arraylist/</guid>
		<description><![CDATA[We use .NET Array and ArrayList objects quite often, but sometimes do not realize the benefits versus consequences of using one or the other. This article explains the differences between these two data structures enabling us to make an informed decision the next time we are required to choose between the two. An Array is [...]]]></description>
			<content:encoded><![CDATA[<p>We use .NET <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">Array</a> and <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList </a>objects quite often, but sometimes do not realize the benefits versus consequences of using one or the other. This article explains the differences between these two data structures enabling us to make an informed decision the next time we are required to choose between the two.</p>
<p>An <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">Array</a> is generally a light-weight (as compared to <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a>), strongly-typed data structure that can hold a pre-defined number of pre-determined element types. <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">Arrays</a> generally perform faster at run-time and consume lesser memory as compared to <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayLists</a>. Also since <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">arrays</a> can be strongly typed, they can take advantage of compile time validation.</p>
<p>An <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList </a>is a class that implements a dynamic collection of objects, that can expand or contract on demand. The type of elements that can be stored in an <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList </a>is always <a href="http://msdn2.microsoft.com/en-us/library/system.object.aspx">System.Object</a>, hence elements retrieved must usually be casted to their original types. <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList </a>implements the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.ilist.aspx">IList</a> interface (which is a descendant of the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.icollection.aspx">ICollection</a> and <a href="http://msdn2.microsoft.com/en-us/library/system.collections.ienumerable.aspx">IEnumerable</a> interfaces), hence the number of elements that can be stored in an <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a> can be altered (and enumerated) on demand. This flexibility, however, comes at the price of some run-time performance. Internally, <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a> objects use <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">arrays</a> to store data. By default, an <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList </a>initially creates an <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">array</a> of 16 elements (.NET 1.x and perhaps 2.0) and then modifies it directly as needed. Once the internal <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">array</a> gets filled, the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a> automatically creates an internal <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">array</a> of double the previous size and copies elements from the old <a href="http://msdn2.microsoft.com/en-us/library/system.array.aspx">array</a> to the new one. This operation obviously is a slight hit on performance as well as memory.</p>
<p>.NET 2.0 introduced <a href="http://msdn2.microsoft.com/en-us/library/6sh2ey19.aspx">Generic Lists</a>, which make it possible to store and retrieve typed objects, hence allowing compile time validation and eliminating the need to cast objects back to their original types. There are various generic lists available in the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.generic.aspx">System.Collections.Generic</a> and <a href="http://msdn2.microsoft.com/en-us/library/system.collections.objectmodel.aspx">System.Collections.ObjectModel</a> namespaces which are suitable for various scenarios. Generally when programming in .NET 2.0, these generic collections are preferred over <a href="http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx">ArrayList</a> objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.softwarerockstar.com/2006/10/array-vs-arraylist/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generic Collection and ReadOnlyCollection Are Actually Not Misplaced</title>
		<link>http://www.softwarerockstar.com/2006/08/generic-collectiont-and-readonlycollectiont-are-actually-not-misplaced/</link>
		<comments>http://www.softwarerockstar.com/2006/08/generic-collectiont-and-readonlycollectiont-are-actually-not-misplaced/#comments</comments>
		<pubDate>Sat, 19 Aug 2006 14:47:00 +0000</pubDate>
		<dc:creator>SoftwareRockstar</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Collection]]></category>
		<category><![CDATA[Collections]]></category>
		<category><![CDATA[decission]]></category>
		<category><![CDATA[generic collections]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[good sense]]></category>
		<category><![CDATA[lt]]></category>
		<category><![CDATA[microsoft]]></category>
		<category><![CDATA[ObjectModel]]></category>
		<category><![CDATA[ReadOnlyCollection]]></category>

		<guid isPermaLink="false">http://mharoon.wordpress.com/2006/08/19/generic-collectiont-and-readonlycollectiont-are-actually-not-misplaced/</guid>
		<description><![CDATA[Since I started using generic collections in .NET Framework 2.0, it always bothered me that Collection&#60;T&#62; and ReadOnlyCollection&#60;T&#62; objects reside in the System.Collections.ObjectModel namespace rather than where they actually belong in the System.Collections.Generic namespace. Today I came across this blog by Krzysztof Cwalina that explains why Microsoft made this decission. Now it makes good sense [...]]]></description>
			<content:encoded><![CDATA[<p>Since I started using generic collections in .NET Framework 2.0, it always bothered me that <a href="http://msdn2.microsoft.com/en-us/library/ms132397.aspx">Collection&lt;T&gt;</a> and <a href="http://msdn2.microsoft.com/en-us/library/ms132474.aspx">ReadOnlyCollection&lt;T&gt;</a> objects reside in the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.objectmodel.aspx">System.Collections.ObjectModel</a> namespace rather than where they actually belong in the <a href="http://msdn2.microsoft.com/en-us/library/system.collections.objectmodel.aspx">System.Collections.Generic</a> namespace. Today I came across <a href="http://blogs.msdn.com/kcwalina/archive/2005/03/15/396086.aspx">this blog by Krzysztof Cwalina</a> that explains why Microsoft made this decission. Now it makes good sense to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.softwarerockstar.com/2006/08/generic-collectiont-and-readonlycollectiont-are-actually-not-misplaced/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 1.950 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-01-25 02:39:00 -->

