DannyD
DannyD

Reputation: 2881

how can I set a value in a setter in c#

I want to add custom logic where my ulong will get set to 1 if it is 0 (default). Here's what I have:

    private ulong quantity;

    public ulong Quantity
    {
        get
        {
            return this.quantity;
        }

        set 
        {
            if (this.Quantity == 0)
            {
                this.quantity = 1;
                return;
            }

            this.Quantity = this.quantity;
        }
    }

However, I'm getting a compile error that says:

Parameter 'value' of 'PurchaseForPayoutRequest.Quantity.set(ulong)' is never used

Upvotes: 0

Views: 2512

Answers (3)

Dhaval
Dhaval

Reputation: 1

You need to set value to this.quantity in your last line

public ulong quantity
{
    get
    {
        return this.quantity;
    }

    set 
    {
        if (value == 0)
        {
            this.quantity = 1;
            return;
        }
        else
        {
            this.quantity = value;
        }
    }
}

in else substitute value with number you want to get assigned when quantity is not 0.

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81503

Make sure you are using properties correctly, you need to use value and make sure you are accessing your backing field. Your example can also be simplified with expression body members and a ?: Operator

private ulong _quantity;

public ulong Quantity
{
   get => _quantity;
   set => _quantity = value == 0 ? (ulong)1 : value;
}

Upvotes: 4

Brendan Green
Brendan Green

Reputation: 11914

You need to be using the contextual keyword value in your setter.

public ulong Quantity
{
    get
    {
        return this.quantity;
    }

    set 
    {
        if (value == 0)
        {
            this.quantity = 1;
            return;
        }

        this.quantity = value;
    }
}

Upvotes: 4

Related Questions