How to find out if a type supports an equality operator

I am creating code that should check for equality using SyntaxGenerator

Example:

 if (property.Type.IsValueType || property.Type == KnownSymbol.String) { if (property.Type.TypeKind == TypeKind.Enum || property.Type.GetMembers("op_Equality").Length == 1) { var valueEqualsExpression = syntaxGenerator.ValueEqualsExpression( SyntaxFactory.ParseName("value"), SyntaxFactory.ParseExpression(fieldAccess)); return (IfStatementSyntax)syntaxGenerator.IfStatement(valueEqualsExpression, new[] { SyntaxFactory.ReturnStatement() }); } ... 

The problem is that this does not handle types like int .

I think I'm looking for something like SupportsValueEquals(ITypeSymbol symbol)

How can I find out if the type of equality supports through == ?

+5
source share
1 answer

As Skeet suggested, I ended up doing anything:

 private static bool HasEqualityOperator(ITypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Enum: case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_String: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: case SpecialType.System_DateTime: return true; } if (type.TypeKind == TypeKind.Enum) { return true; } foreach (var op in type.GetMembers("op_Equality")) { var opMethod = op as IMethodSymbol; if (opMethod?.Parameters.Length == 2 && type.Equals(opMethod.Parameters[0].Type) && type.Equals(opMethod.Parameters[1].Type)) { return true; } } return false; } 

Please comment if you noticed stupid things.

0
source

Source: https://habr.com/ru/post/1261494/


All Articles