Archive for January, 2012

Dynamically Generate A Class From An Interface Part 1

Monday, January 30th, 2012

As part of an overall dynamic system that is able to compose objects for use in Dependency Injection, I’d like to be able to take any Interface definition consisting only of properties and turn it into a usable class with an instantiated object being returned.

In order to do this, several parts will be needed:

1.  Method which inspects a defined interface and returns source code for a class

2.  Method which compiles the source code, instantiates an object of the given type and returns it to the caller.

In order to get started, we’ll define a class to actually hold the source code for the class and the name of the class to make it easier as we go through this exercise.  This class should be fairly straightforward and easy to follow:



public class ClassSourceCode

{

public ClassSourceCode(string className, string sourceCode):this()

{

ClassName = className;

SourceCode = sourceCode;

}

public ClassSourceCode()

{

}

public string ClassName { get; set; }

public string SourceCode { get; set; }

}


Our next step is to create a method that will take a look at the properties of the passed in interface and generate source code based on it.  Our method is going to take advantage of generic type parameters to receive the interface that we’ll be working with.  Unfortunately, we don’t have the option of restricting the parameter to an interface, so we’ll have to use the superset class which includes interfaces.  In order to make sure that we really did receive an interface and not a class, we’ll throw in a guard clause.



public ClassSourceCode Generate<T>() where T : class

{

if (!typeof(T).IsInterface)

{

throw new Exception("Interface required for class generation");

}


Next we’ll do a few “housekeeping chores”, create a ClassSourceCode object to be returned and set the ClassName based on the name of the interface; assuming of course that the interface is named using the standard convention of adding a capital I to the front of it’s descriptive name. Since we’ll be doing a great deal of string concatenation, we’ll use a StringBuilder to avoid the performance costs associated with the string class while creating our source code.



ClassSourceCode classSourceCode = new ClassSourceCode();

classSourceCode.ClassName = typeof(T).Name.Remove(0,1);

StringBuilder sourceCode = new StringBuilder();


Now we begin with actually creating the source code for the class.  In order to make the class easier to work with, we’ll set the namespace to the same namespace utilized by the interface passed in and of course the class will implement the passed in interface in it’s definition.



sourceCode.AppendLine("namespace " + typeof(T).Namespace);

sourceCode.AppendLine("{");

sourceCode.AppendLine("public class " + classSourceCode.ClassName + " : " + typeof(T).FullName);

sourceCode.AppendLine("{");


Now we just need code to represent each property within the interface.  Using System.Reflection we’re able to loop through all of the properties described by the passed in interface.



foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())

{


This next section of code is “somewhat optional”, for the system I’m describing their should be no need for Read Only or Write Only properties.  All properties should be Read/Write and would be handled in the very simple else clause in the next section of code.  With that said, I’ve kept this portion in as this code could easily be adapted to handle other instances.  Perhaps you’re looking to create an add-in that will generate class source code from an interface to save yourself time, but will then take the generated class even further, not simply generate and instantiate at run-time as I intend to do.



if (!(propertyInfo.CanWrite &amp;amp;amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;amp;amp; propertyInfo.CanRead))

{

sourceCode.AppendLine("private " + propertyInfo.PropertyType + " " + propertyInfo.Name.ToLower() + ";");

sourceCode.AppendLine("public " + propertyInfo.PropertyType  + " " + propertyInfo.Name);

sourceCode.AppendLine("{");

if (propertyInfo.CanRead)

{

sourceCode.AppendLine("get");

sourceCode.AppendLine("{");

sourceCode.AppendLine(" return " + propertyInfo.Name.ToLower() + ";");

sourceCode.AppendLine("}");

}

if (propertyInfo.CanWrite)

{

sourceCode.AppendLine("set");

sourceCode.AppendLine("{");

sourceCode.AppendLine(propertyInfo.Name.ToLower() + " = value;");

sourceCode.AppendLine("}");

}

sourceCode.AppendLine("}");

}


This is the simple case for a property that is Read/Write.



else

{

sourceCode.AppendLine("public " + propertyInfo.PropertyType + " " + propertyInfo.Name + " { get; set; }");

}

}

sourceCode.AppendLine("}");

sourceCode.AppendLine("}");


At this point, we have the source code representing our class and simply need to add it to the ClassSourceCode object and return it to the caller.



classSourceCode.SourceCode = sourceCode.ToString();

return classSourceCode;

}

Now that we have a Method which can accept an interface, interrogate it using Reflection and create source code for a class that implements that interface, we can move onto step 2 which is to actually compile the code and instantiate an object based on it.

Dynamically Generate A Class From An Interface Part 2

In this follow up post I’ll walk you step by step through compiling code at runtime using the CSharpCodeProvider and instantiating objects from it.

Abstract Classes Versus Interfaces

Tuesday, January 17th, 2012

Had a very interesting question on a recent interview: “What’s the difference between an abstract class and an interface? Why would you choose to use one over another?”

How exactly do you answer this question off the top of your head in an interview format and truly do the subject justice? I simply had to hope that the interviewer was more interested in thought processes and an abstract discussion than concrete information.

After having time to fully digest the question and put my thoughts together, here is my attempt at an intelligent answer, which may not be much better than my interview answer.

My biggest problem with this question is that it pre-supposes that the two are interchangeable. While an argument can be made that it is possible to use them interchangeably, it ignores their strengths, weaknesses and design purposes.

Abstract Class:
Full or Partial implementation
Inheriting classes may only inherit from one class
Updates passed along to inheriting classes
Great for classes that are similar (Dog and Cat both inherit from Animal)

Interfaces:
Only define input/output contract, no implementation
Classes may implement multiple interfaces
Once defined, should never change
Great for functionality used in many dis-similar classes

This still doesn’t quite answer the question, another good way to look at it is Nouns versus Verbs. Abstract Classes represent a Noun, such as in the example given above of Dog and Cat inheriting from Animal, while interfaces represent a Verb. If I were representing my dog Heidi as a class, she would inherit from Dog, but would need to implement the interfaces IJumpOnEveryone and IChewOnYourHand.

But in the end, I’m not sure we’ll come to a conclusion of what’s “right” and what’s “wrong” in this. While their are the obvious cases that neatly fit into either/or, as always I hate the cases where I can make a valid argument for either way. It’s times like those where I hope that one presents a clear disadvantage over the other to help me select.

I’d love to hear others opinions on this, please comment.