I am trying to overload the unary operator ! in C# , so that it receives a Visibility
. My goal is for it to invert the visibility of a controller.
Example:
Button_Click(object sender, RoutedEventArgs e)
{
ControlName.Visivility = !ControlName.Visivility;
}
To do this, I have done the following code.
namespace Test
{
//A namespace cannot directly contain a members such as fields or methods.
public static Visibility operator !(Visibility visibility)
{
if (visibility == Visibility.Visible) return Visibility.Hidden;
else return Visibility.Visible;
}
class VisivilityConverter
{
//The parameter of unary operator must be the containing type.
public static Visibility operator !(Visibility visibility)
{
if (visibility == Visibility.Visible) return Visibility.Hidden;
else return Visibility.Visible;
}
}
}
But I get these 2 errors:
- Error 1: A namespace cannot directly contain a member such as fields or methods.
- Error 2: The parameter of unary operator must be the containing type.
If there is a way to do this, I hope someone can help me.
Let me tell you, you will never be able to overload
Visibility
, since itVisibility
is aenum
, and operator overloads apply only toclases
andstruct
.At most you will be able to create a custom class which gives you said functionality, but what you are trying to do is not possible.
The only way to override the operators is by defining them in the class itself and it
Visibility
is an enum.What you can do is create an extender method that negates the value:
Use:
Or you can create an extender method that toggle the property
Visibility
. If thisVisible
changes it toHidden
and vice versa:Use: