// Create a CodeMemberField object representing a private string field CodeMemberField field = new CodeMemberField("System.String", "fieldName"); field.Attributes = MemberAttributes.Private; // Add the field to a CodeTypeDeclaration object representing a class CodeTypeDeclaration classDecl = new CodeTypeDeclaration("MyClass"); classDecl.Members.Add(field);
// Create a CodeMemberField object representing a public int field with an initial value CodeMemberField field = new CodeMemberField("System.Int32", "fieldName"); field.Attributes = MemberAttributes.Public; field.InitExpression = new CodePrimitiveExpression(42); // Add the field to a CodeTypeDeclaration object representing a struct CodeTypeDeclaration structDecl = new CodeTypeDeclaration("MyStruct"); structDecl.IsStruct = true; structDecl.Members.Add(field);This example creates a public int field named "fieldName" with an initial value of 42 in a CodeTypeDeclaration object representing a struct. The IsStruct property is set to true to indicate that the type is a struct. The CodePrimitiveExpression class is used to specify the initial value of the field. Package library: System.CodeDom.