Dependency Frameworks and Parameterized Constructors

April 23rd, 2012 Comments

Most dependency injection frameworks support some kind of object initialization through parameterized constructors. The question is whether or not it’s a good idea to use that feature of DI frameworks.

Consider the following code:
Read more…

Finding Distinct Elements In A List(T)

August 4th, 2011 2 comments

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<T> interface in our target class. That’s what Distinct() uses in order to compute whether one element is the same as another element. Implementing IEqualityComparer<T>, however, is not so straightforward as it requires us to override Equals() and GetHashCode() methods. Most of the times if all we need to do is just to find non-duplicated elements in a given list, IEqualityComparer<T> route seems like an overkill. Read more…

Using IXmlSerializable To Overcome “not expected” Error On Derived Classes

December 10th, 2006 16 comments

This article extends upon Simon Hewitt’s article on CodeProject. It is strongly recommended that you read Simon’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 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’s built-in support for XML serialization, all this can be achieved with only a few lines of code using the System.Xml.Serialization.XmlSerializer object.

PROBLEM
The problem with XmlSerializer 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’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 System.InvalidOperationException if the public member was set to a derived type.

WORKAROUND
The workaround to above problem has generally been resorting to custom XML serialization, which can get pretty complicated at times.

SOLUTION
An ingenious solutions was discovered by Simon Hewitt using the System.Xml.Serialization.IXmlSerializable 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.

Using C# generics, I took the liberty of extending Simon’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.

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 "/> class.
///
public CustomSerializer()
{
}

///
/// Initializes a new instance of the "/> 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("type"));

// 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("type", _parameters.GetType().ToString());
new XmlSerializer(_parameters.GetType()).Serialize(writer, _parameters);
}

#endregion IXmlSerializable Implementation

}
}

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:

[XmlElement(Type = typeof(CustomSerializer))]

Array vs. ArrayList

October 16th, 2006 Comments

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 generally a light-weight (as compared to ArrayList), strongly-typed data structure that can hold a pre-defined number of pre-determined element types. Arrays generally perform faster at run-time and consume lesser memory as compared to ArrayLists. Also since arrays can be strongly typed, they can take advantage of compile time validation.

An ArrayList 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 ArrayList is always System.Object, hence elements retrieved must usually be casted to their original types. ArrayList implements the IList interface (which is a descendant of the ICollection and IEnumerable interfaces), hence the number of elements that can be stored in an ArrayList can be altered (and enumerated) on demand. This flexibility, however, comes at the price of some run-time performance. Internally, ArrayList objects use arrays to store data. By default, an ArrayList initially creates an array of 16 elements (.NET 1.x and perhaps 2.0) and then modifies it directly as needed. Once the internal array gets filled, the ArrayList automatically creates an internal array of double the previous size and copies elements from the old array to the new one. This operation obviously is a slight hit on performance as well as memory.

.NET 2.0 introduced Generic Lists, 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 System.Collections.Generic and System.Collections.ObjectModel namespaces which are suitable for various scenarios. Generally when programming in .NET 2.0, these generic collections are preferred over ArrayList objects.