CodeDOM Best Practice: Use Reflection To Get Names
The use of constants instead of strings in code is well known. Code such as this:
public class MyClass
{
public void MyMethod()
{
string myString = "Omer";
// Do Some Magic
}
}
Should be transformed to this:
public class MyClass
{
private const string Omer = "Omer";
public void MyMethod()
{
string myString = Omer;
// Do Some Magic
}
}
But what do you do when you need to generate code that calls the GetType method on your local variable?
Well, normally you could do this:
public class MyClass
{
private const string MyVariable = "myVariable";
private const string GetType = "GetType";
public void MyMethod()
{
CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(MyVariable), GetType);
// Do Some Magic
}
}
This would work well and some would agree that this is the best form.
However, when generating code using CodeDOM, there's two more 'times' in which your code may break. There's the standard compile-time and run-time, but they are the compile-time and run-time of your generator's code. There are also the compile-time and the run-time of your generated code, both of which you can not control. Changes in member/type names may break your code during the third 'time', the generated code's compile time.
What do we do, then? We use Reflection, which allows us to write code like this:
public class MyClass
{
private const string MyVariable = "myVariable";
private static readonly string GetType = typeof(System.Object).GetMember("GetType")[0].Name;
public void MyMethod()
{
CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(MyVariable), GetType);
// Do Some Magic
}
}
Sure, it takes more time for your generator to load, but it transfers the problem from the generated code to the generator's run-time. This way, your code would
not even run which is way better, in my opinion, than run and produce errorneous code.