Skip to content

Instantly share code, notes, and snippets.

@Vannevelj
Last active August 29, 2015 13:58
Show Gist options
  • Save Vannevelj/9964963 to your computer and use it in GitHub Desktop.
Save Vannevelj/9964963 to your computer and use it in GitHub Desktop.
Generating the .Equals() method through CodeDom
private void AddEqualsMethod(ref CodeTypeDeclaration type, TinyType tinyType)
{
// Create method
var method = new CodeMemberMethod()
{
Name = "Equals",
Attributes = MemberAttributes.Public | MemberAttributes.Override,
ReturnType = new CodeTypeReference(typeof (bool)),
};
method.Parameters.Add(new CodeParameterDeclarationExpression(typeof (object), "o"));
// Check for type equality
var isTypeEqual = new CodeBinaryOperatorExpression
{
Left = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetType"),
Operator = CodeBinaryOperatorType.IdentityEquality,
Right = new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("o"), "GetType")
};
var conditionBody = new CodeConditionStatement { Condition = isTypeEqual };
// Cast Object to the correct type
var tempVar = new CodeVariableDeclarationStatement(tinyType.Name, "tmp");
var cast = new CodeCastExpression
{
TargetType = new CodeTypeReference(tinyType.Name),
Expression = new CodeArgumentReferenceExpression("o")
};
tempVar.InitExpression = cast;
// Add return check on the .Value property
var trueCondition = new CodeBinaryOperatorExpression
{
Left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Value"),
Operator = CodeBinaryOperatorType.IdentityEquality,
Right = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("tmp"), "Value")
};
// Add to return condition
var trueReturn = new CodeMethodReturnStatement(trueCondition);
// Add elements to true-if-body
conditionBody.TrueStatements.Add(tempVar);
conditionBody.TrueStatements.Add(trueReturn);
// Fallthrough return statement
conditionBody.FalseStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(false)));
method.Statements.Add(conditionBody);
type.Members.Add(method);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment