Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeDom generic type constraint

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.

like image 285
Fionn Avatar asked Jan 04 '09 14:01

Fionn


2 Answers

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.

like image 182
Max Galkin Avatar answered Oct 13 '22 22:10

Max Galkin


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);

like image 38
IS4 Avatar answered Oct 14 '22 00:10

IS4