Archive

Posts Tagged ‘Reflections’

C# Object To Interface Caster Utility

April 23rd, 2009 9 comments

Introduction

Here I describe a unique way of casting any object to an interface that it actually exposes, even though it does not formally implement the particular interface. In order to get the idea what I’m trying to propose here, consider examples below.

Lets say you’re utilizing 3rd party libraries(LibA and LibB) that are dealing with persons. These libraries have PersonLibA and PersonLibB classes defined and are exposing instances of these persons. Most likely they would expose similar public interface and would have properties like Name, EMail, Address, DateOfBirth, etc.  I’m almost sure that you would like to access these persons uniformly. If you had the source code of these components, you could define a common interface and implement PersonLibA and PersonLibB classes from your newly defined interface. However, if the source code is not available that would not work out. The only thing left to do is to define wrapper classes for each of person classes and implement the common interface.
Read more…

Attached Files:

C# Object Cloning Machinery

March 16th, 2009 3 comments

Introduction

In most cases, no matter what area of software development you are involved in, you will need a functionality of cloning your objects. The .NET Framework provides you 3 ways of achieving your object copying goal:

  1. Implement the ICloneable interface, and develop cloning functionality manually for each class involved in your desired cloning.
  2. Serialize you object to binary stream and deserialize it utilizing BinaryFormatter and MemoryStream classes. In this case your classes will need to be Serializable.
  3. Clone using Reflections.

Read more…

Attached Files: