4 07 2011

Everything in C# inherits from System.Object and as a result every instance of an object has access to the GetType() method. This method returns an instance of Type that represents the exact runtime type of the instance it is called on.

This method came in very handy today as I had to keep a record in memory of the type of every object I serialized to disk in order to deserialize it correctly later. So I set up a Listand stored each type as I serialized the data (actually I did more than that, see code). I think that relying on GetType() is acceptable in those sort of situations, if you find that your code uses it heavily in many places that’s a symptom of a design that needs rethinking.

private class TypeTracker
    public class ColumnComparisonTypes
        public Type SrcType { get; set; }
        public Type TgtType { get; set; }

        public bool Complete { get { return SrcType != null && TgtType != null; } }

    private readonly List m_ColumnComparisonTypes;
    private bool Complete
      get { return m_ColumnComparisonTypes.TrueForAll(c => c.Complete); }  

    public TypeTracker(ColumnComparisonSettingsCollection columnComparisonSettingsCollection)
        m_ColumnComparisonTypes = new List(columnComparisonSettingsCollection.Count);
        for(int i=0; i<columnComparisonSettingsCollection.Count; ++i)
            m_ColumnComparisonTypes.Add(new ColumnComparisonTypes());

    public ColumnComparisonTypes this[int i]
        get { return m_ColumnComparisonTypes[i]; }

    public void Track(RowComparisonResult rowComparisonResult)
        if (rowComparisonResult == null) throw new ArgumentNullException("rowComparisonResult");
        if (Complete) return;

        for(int i = 0; i < rowComparisonResult.CellResults.Count; ++i)
            var cellResult = rowComparisonResult.CellResults[i];

            if (cellResult.SourceValue != null && m_ColumnComparisonTypes[i].SrcType == null)
                m_ColumnComparisonTypes[i].SrcType = cellResult.SourceValue.GetType();
            if (cellResult.TargetValue != null && m_ColumnComparisonTypes[i].TgtType == null)
                m_ColumnComparisonTypes[i].TgtType = cellResult.TargetValue.GetType();




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: