7

I have a VB class which overloads the Not operator; this doesn't seem to be usable from C# applications.

Public Shared Operator Not(item As MyClass) As Boolean
    Return False
End Operator

I can use this in VB.NET:

If Not MyClassInstance Then
    ' Do something
End If

I am trying to us this in a C# application but it won't build.

if (!MyClassInstance) 
{ 
     // do something
}

I get the error

Operator '!' cannot be applied to operand of type 'MyClass'

Can anyone tell me what I am missing?

1
  • try writing the class name with parameter braces because you have to call that function that's returning a boolean value. i.e if(!MyClassInstance()) { // do something } Commented Dec 12, 2014 at 18:59

1 Answer 1

15

The Not operator in VB.NET is a bitwise operator, it produces the one's complement of its operand. It doesn't have the equivalent of C#'s ! operator, a logical operator. You must use the equivalent bitwise operator in C# to use your VB.NET operator overload:

if(~MyClassInstance) 
{ 
     // do something
}

You can write a function in VB.NET that will map to the C# logical operator. That needs to look like this:

<System.Runtime.CompilerServices.SpecialName> _
Public Shared Function op_LogicalNot(item As MyClass) As Boolean
    Return False
End Function
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explaination, unfortunately if I use the op_LogicalNot I am not allowed to also use the VB Not operator, so I can have it strange in VB or strange in C#. I will just stick to using the bitwise operator in C#.
Fascinating, Visual studio complains that a method with the same name is declared twice, but it does build and run. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.