Search code examples
c#unity-game-engineexceptionstack-overflow

Implicit cast caused StackOverflowException in Unity


I have a custom Class called BoolReference. I am using implicit cast to assign bool values to this class without calling it's Value property. Here is the code where second cast method causes stack overflow and can someone help me to fix this?

[System.Serializable]
public class BoolReference {
[SerializeField]
private BoolVariable Variable;

public bool Value {
    get => Variable.Value;
    set {
        Variable.Value = value;
    }
}

public static implicit operator bool(BoolReference bRef) => bRef.Value;
public static implicit operator BoolReference(bool b) => b;

}

This is usage which causes the exception

public BoolReference IsInPlay;

void Awake() {
    IsInPlay = false;    
}

If i write IsInPlay.Value = false, then everything is ok


Solution

  • Actually returning a BoolReference in the conversion operator worked for me:

    using System;
    
    public class BoolVariable {
        public bool Value;
    }
    
    public class BoolReference {
    
    private BoolVariable Variable;
    
    public bool Value {
        get => Variable.Value;
        set {
            Variable.Value = value;
        }
    }
    
    public static implicit operator bool(BoolReference bRef) => bRef.Value;
    public static implicit operator BoolReference(bool b){
        BoolReference br = new BoolReference();
        br.Variable = new BoolVariable();
        br.Value=b;
        return br;
    }
    
    }   
    public class Program
    {
        static BoolReference r;
        public static void Main()
        {
            r = false;
            Console.WriteLine(r);
            r = true;
            Console.WriteLine(r);
        }
    }
    

    ...which prints:

    false
    true