var stmts = new CodeStatementCollection(); var forLoop = new CodeIterationStatement( new CodeVariableDeclarationStatement(typeof(int), "i", new CodePrimitiveExpression(0)), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(10)), new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))) ); stmts.Add(forLoop);
var stmts = new CodeStatementCollection(); var tryCatch = new CodeTryCatchFinallyStatement( new CodeStatement[] { new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Try block")), new CodeThrowExceptionStatement(new CodeObjectCreateExpression("System.Exception", new CodePrimitiveExpression("Exception message"))) }, new CodeCatchClause[] { new CodeCatchClause("ex", new CodeTypeReference("System.Exception"), new CodeStatement[] { new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodeVariableReferenceExpression("ex.Message") ) }) }, new CodeStatement[] { new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Finally block") ) } ); stmts.Add(tryCatch);In this example, a CodeStatementCollection is created and a CodeTryCatchFinallyStatement is added to it. The CodeTryCatchFinallyStatement represents a try-catch-finally block with statements in the try block, a catch clause for catching System.Exception, and statements in the finally block. Overall, CodeStatementCollection is a useful component of System.CodeDom for generating source code programmatically in C#.