If (instance) / implicit boolean conversion in user class

I have the following class:

public class InterlockedBool { private int _value; public bool Value { get { return _value > 0; } set { System.Threading.Interlocked.Exchange(ref _value, value ? 1 : 0); } } public static bool operator ==(InterlockedBool obj1, bool obj2) { return obj1.Value.Equals(obj2); } public static bool operator !=(InterlockedBool obj1, bool obj2) { return !obj1.Value.Equals(obj2); } public override bool Equals(bool obj) { return this.Value.Equals(obj); } } 

My question is: can I check if the value is == true without == true ? The operator overrides the work, but can I also use it like this?

 InterlockedBool ib = new InterlockedBool(); if (ib) { } 

Instead (this works, but usually I omit the == true instructions in if .

 if (ib == true) { } 
  1. And how to assign it to a value without using .Value = ?

Thanks for the help:)

+5
source share
2 answers

You should be able to convert your object to and from logical

Implicit conversion

Your object to boolean:

 public static implicit operator bool(InterlockedBool obj) { return obj.Value; } 

Then a boolean for your object:

 public static implicit operator InterlockedBool(bool obj) { return new InterlockedBool(obj); } 

Then you can check it out:

 InterlockedBool test1 = true; if (test1) { //Do stuff } 

Explicit conversion

If you want users of this class to know that a conversion is occurring, you can force an explicit action:

 public static explicit operator bool(InterlockedBool obj) { return obj.Value; } public static explicit operator InterlockedBool(bool obj) { return new InterlockedBool(obj); } 

Then you must explicitly specify your objects:

 InterlockedBool test1 = (InterlockedBool)true; if ((bool)test1) { //Do stuff } 

EDIT (due to OP comment)

In the conversion from boolean to your object, I call a constructor that you did not mention, here is how I built it:

 public InterlockedBool(bool Value) { this.Value = Value; } 

Therefore, setting the value is guaranteed by thread safety.

+5
source

You can define an implicit conversion in bool:

 public static implicit operator bool(InterlockedBool obj) { return obj.Value; } 
+4
source

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


All Articles