Search code examples
c#returnreturn-value

c#: Have class return value without direct variable reference


I'm trying to figure out if it's possible to create a class that returns a value by default without a method/variable reference.

public class Attribute
{
    public int defaultValue = _base + _mods;

    private int _base;
    private int _mods;

    public Attribute (int b, int m)
    {
        _base = b;
        _mods = m;
    }
}

public class UseAttribute
{
    private Attribute att;

    public Start()
    {
        att = new Attribute(5,2);
    }

    public void CheckAttribute()
    {
        console.WriteLine("att: " + att); //Outputs:"att: 7"
    }
}

Is this something that can be done, or would I have to always use att.defaultValue ?


Solution

  • There is a way how to do this and it would be implicit or explicit conversion.

    public class Attribute
    {  
        private int _base;
        private int _mods;
    
        public Attribute (int b, int m)
        {
            _base = b;
            _mods = m;
        }
    
        public static implicit operator int(Attribute attr) => attr._base + attr._mods;
    
        public override string ToString() => $"{this._base + this._mods}";
    }
    
    public class UseAttribute
    {
        private Attribute att;
    
        public UseAttribute()
        {
            att = new Attribute(5,2);
        }
    
        public void CheckAttribute()
        {
            console.WriteLine("att: " + att); //Outputs:"att: 7"
        }
    }
    

    In the end I would not go for it and better use method or property.