Sunday, April 17, 2011

How to use CodeVariableDeclaraionStament to declare Arrays

CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(p.ParameterType, p.Name,
                       new CodePrimitiveExpression(INTARR()));

Consider the above code. and when i run my project in debug mode,these are the values that get stored in p.ParameterType and p.Name.

p.ParameterType = {Name = "Int32[]" FullName = "System.Int32[]"}
p.Name = "x"

and INTARR() is a method that returns an Array of Integers.

but i get the error, "Invalid Primitive Type: System.Int32[]. Consider using CodeObjectCreateExpression."

How can i use CodeObjectCreateExpression for the above code,i.e I want to pass an Array of integers in CodeVariableDeclarationStatement.?

From stackoverflow
  • based on this link I think it should be like this

    CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(typeof(Int32[]), "x",
                           new CodePrimitiveExpression(INTARR()));
    

    So maybe this?:

    CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(typeof(Int32[], "x",
                           new CodePrimitiveExpression(INTARR()));         
    
    p.ParameterType = typeof(Int32);
    p.Name = "x";
    
  • Arrays are not primitive. You need to use CodeArrayCreateExpression:

    Int32[] ints = INTARR();
    CodeExpression[] intExps = new CodePrimitiveExpression[ints.Length];
    for (int i = 0; i < ints.Length; i++)
       intExps[i] = new CodePrimitiveExpression(ints[i]);
    CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(
       "Int32[]", "x", new CodeArrayCreateExpression("Int32", intExps));
    

0 comments:

Post a Comment