Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ref over return

I'm making an "adapter" base class that instantiates a private struct. The struct is exposed to inheritors via an abstract Configure() method, so they can set properties on it. Implementation as follows:

public abstract class PaymentAdapter {

    private PaymentObject p = new PaymentObject();

    protected PaymentObject CreditCardPayment {
        get { return p; }
    }

    protected abstract void Configure(PaymentObject payment);

    public MyResponse ProcessPayment() {
        // Run the adapter's setup
        Configure(p);

        // Charge the customer
        var chargeResult = p.DoSomething();

        return new MyResponse {
            MyResult = chargeResult
        };
    }
}

Those of you who are observant will see what the following line needs some attention:

protected abstract void Configure(PaymentObject payment);

When overridden in a concrete class, this method (almost) gives the consumer the opportunity to modify the struct's properties directly. This is the desired result.

My question is - should I use a ref argument, or change the void to PaymentObject, making the consumer return an instance themselves?

Method 1:

protected abstract PaymentObject Configure(PaymentObject payment);

Method 2:

protected abstract void Configure(ref PaymentObject payment);

So, when inheriting the class, the consumer would have to do the following:

Method 1:

public class MyConsumer : PaymentAdapter {
    #region Overrides of PaymentAdapter

    protected override PaymentObject Configure(PaymentObject payment) {
        payment.AProperty = "Something";
            return payment;
    }

    #endregion
}

Method 2:

public class MyConsumer : PaymentAdapter {
    #region Overrides of PaymentAdapter

    protected override void Configure(ref PaymentObject payment) {
        payment.AProperty = "Something";
    }

    #endregion
}

Apart from the slight change in syntax, are there any other differences at all? Is this a preference thing, or are there benefits I can't see to using one over the other?

As there's slightly less code, I would be inclined to use the "ref" method, contrary to all my years of exclusively returning objects from methods. This seems like a perfect case for a ref argument - it makes the consumer's job slightly easier, and means I'm not setting objects all over the place.

like image 613
Spikeh Avatar asked Jun 16 '26 20:06

Spikeh


1 Answers

Reference types are passed by reference by default, so you don't have to use ref keyword here.

If your type is a Struct you should definitely use return statement, because structures should be immutable (why? Read answers for Why are mutable structs “evil”? and Why are C# structs immutable?)

like image 100
MarcinJuraszek Avatar answered Jun 18 '26 11:06

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!