I have bit confusion about parameters. When we should have to use reference parameter and when should have to use value type parameters while programming with methods/functions in c# ?
I have bit confusion about parameters. When we should have to use reference parameter
Share
You need to be very clear on the distinction between reference types vs value types, and “by value” parameters vs “by reference” parameters.
I have articles on both topics:
The two interact somewhat when using a “by value” parameter which is a reference type: in this case the value which copied by value is the reference itself; you can still modify the object that the reference refers to:
Note that this isn’t the same thing as pass-by-reference semantics… if
SomeMethodwere changed to include:then that wouldn’t make the
buildervariable null. However, if you also changed thexparameter to beref StringBuilder x(and changed the calling code appropriately) then any changes tox(such as setting it to null) would be seen by the caller.When designing your own API, I would strongly advise you to almost never use
reforoutparameters. They can be useful occasionally, but usually they’re an indication that you’re trying to return multiple values from a single method, which is often better done with a type specifically encapsulating those values, or perhaps aTupletype if you’re using .NET 4. There are exceptions to this rule, of course, but it’s a good starting point.