CodeMemberProperty property = new CodeMemberProperty() { Name = "MyProperty", Type = new CodeTypeReference(typeof(int)), Attributes = MemberAttributes.Public | MemberAttributes.Final, HasGet = true, HasSet = false }; property.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(42)));
CodeMemberProperty property = new CodeMemberProperty() { Name = "MyProperty", Type = new CodeTypeReference(typeof(int)), Attributes = MemberAttributes.Public | MemberAttributes.Final, HasGet = true, HasSet = true }; CodeExpression value = new CodePropertySetValueReferenceExpression(); CodeConditionStatement condition = new CodeConditionStatement( new CodeBinaryOperatorExpression(value, CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(0)), new CodeThrowExceptionStatement( new CodeObjectCreateExpression( new CodeTypeReference(typeof(ArgumentException)), new CodePrimitiveExpression("Value cannot be negative.") ) ) ); property.SetStatements.Add(condition); property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(null, "_myField"), value));In this example, we create a CodeMemberProperty instance that represents a read-write property member called MyProperty of type int with validation that checks if the value is negative. If the value is negative, it throws an exception of ArgumentException with a message "Value cannot be negative". Otherwise, it assigns the value to a private field _myField. Overall, System.CodeDom.CodeMemberProperty is used to create property members in C# code. It allows us to set various properties of a property member, such as its name, type, attributes, get and set statements, which can be useful when generating C# code dynamically. It is a part of the System.CodeDom namespace of Microsoft .NET Framework.