CodeDom generic type constraint
Asked Answered
B

2

12

Is there a way to generate a class constraint with CodeDom.

Because when I use something like

var method = new CodeMemberMethod();
var genericParam = new CodeTypeParameter("InterfaceType");
genericParam.Constraints.Add("class");
method.TypeParameters.Add(genericParam);

the generated code is like

private InterfaceType GetImpl<InterfaceType>()
    where InterfaceType : @class
{
}

The best workaround i found is to use a leading whitespace before the class

genericParam.Constraints.Add(" class");

But this seems to be at best a workaround.

Billybillycock answered 4/1, 2009 at 14:29 Comment(0)
B
7

It seems that there is no straigntforward way to specify that constraint. Neither for the "struct" constraint.

For the "T : new()" constraint use the flag HasConstructorConstraint

For the rest use CodeTypeReference as in this msdn example.

Bran answered 10/6, 2009 at 14:50 Comment(0)
C
1

I also use zero-width space ("\x200Bclass") instead of normal space. Then I replace it in final string with empty string: .Replace("\x200B", string.Empty);

Calaboose answered 2/6, 2012 at 20:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.