1

I think it is more clear that if I pass reference type parameter to the method, that will be changed inside method to add ref keyword like this

void Foo(ref Boo boo)
{
    boo.Value = 6;
}

, even this doesn't affect program execution any way and by default objects are passed by reference and I don't want to change reference inside void like this:

void Foo(ref Boo boo)
{
    boo = new Boo();
}

because I think that with ref it is clear from method signature that I will change Boo inside instead of just reading it. Do you agree? What do you think about this?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Brans Ds
  • 4,039
  • 35
  • 64
  • http://stackoverflow.com/questions/961717/what-is-the-use-of-ref-for-reference-type-variables-in-c – Mehdi Khademloo Sep 26 '14 at 10:19
  • ref must be explicitly used on the Foo call like `Foo(ref boo)` so yes, that already makes it quite obvious the object is going to get changed in the function. – Hatted Rooster Sep 26 '14 at 10:20
  • You ask for opinions, so the question should be closed. However, no, you think that it is clearer but to me it is the exact contrary – Steve Sep 26 '14 at 10:20
  • I don't think using the ref keyword really adds any value. If we are passing in a mutable reference type it is safe to assume it might be mutated. – ChaosPandion Sep 26 '14 at 10:20
  • 1
    @JameyD actually, that **does not** mean "the object is going to get changed". It means that the parameter value is passed by reference, and thus the *parameter value* can change. The parameter value **is not** the object, and is **never** the object. The parameter value is the *reference* to the object. `ref`, in the context of reference-types, merely says: *if* the caller reassigns the parameter value to a different reference: the caller will see that change – Marc Gravell Sep 26 '14 at 10:23

1 Answers1

4

I think it is more clear that if I pass reference type parameter to the method, that will be changed inside method to add ref keyword like this

No, that just demonstrates that you aren't familiar with the intended meaning of ref. It is entirely normal and idiomatic for methods to manipulate objects that are made available to them. If you don't want that: write immutable objects.

Do not do this. The lack of ref does not imply any kind of const.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    The fact that purity can't be enforced in C# other than by making objects immutable, doesn't make it 'idiomatic' IMHO. It is normal in the sense that a lot of developers don't keep their 'query' and 'action' methods apart, so you often can't tell what a method does by looking at its signature. That doesn't mean it's a good thing, though. – bstenzel Sep 26 '14 at 10:44