GrandMasterFlush
GrandMasterFlush

Reputation: 6409

Instantiating a non-primitive type with CodeDom

I'm trying to use CodeDom to instantiate an instance of System.Drawing.Font but I can't work out how to create a new type, specifically for the FontFamily and FontStyle parameters.

If I execute the following code:

CodeExpression[] parms = new CodeExpression[3];

parms[0] = new CodePrimitiveExpression(((System.Drawing.Font)value).FontFamily.Name);
parms[1] = new CodePrimitiveExpression(((System.Drawing.Font)value).Size);
parms[2] = new CodePrimitiveExpression(((System.Drawing.Font)value).Style);

codeObjectCreateExpression = new CodeObjectCreateExpression("System.Drawing.Font", parms);

I get an error

Invalid Primitive Type: System.Drawing.FontStyle. Consider using CodeObjectCreateExpression.

From reading around, I know I have to use CodeObjectCreateExpression to create an instance of a type, but I'm unsure how to assign anything apart from primitives to it.

Upvotes: 1

Views: 1500

Answers (1)

svick
svick

Reputation: 244968

If you want to use any object, then you can't do that (at least not without using hacks like serialization or accessing private fields using reflection). That's because CodeDOM tree has to be translated to C# (or another .Net language). And CodeDOM has no idea how to write code that would construct that object (Should it call a constructor? Which one? Or a factory method? Or something else?).

But if it's just enums (like FontStyle) that you have problems with, you can get its value as if you were accessing a static field on the enum type:

new CodeFieldReferenceExpression(
    new CodeTypeReferenceExpression("System.Drawing.FontStyle"),
    ((System.Drawing.Font)value).Style.ToString())

Upvotes: 3

Related Questions