1

I have a quite simple question on convention, when should methods actually have ref or out parameters in C#?

How does this fit in to following good OOP and not just laziness or bad design?

As one example I have come across the class MembershipProvider (from .NET System.Web.Security) that has a CreateUser method that has an out for MembershipCreateStatus and returns a MembershipUser.

Is the reason behind it basically for when there are cases information is needed from the method but it would not be appropriate/can not be returned from the method?

Thanks


3 답변


2

just think of following system:

you have a method, which returns an object and some sort of status (or even more instances). now you have 2 options for the return-value:

  1. create a wrapper, which encapsulates the bool (or enum) state and the actual result
  2. separate those n instances

i prefer wrappers, if i have to return more than 2 instances. if the signature only handles a state and a result, i prefer out/ref-style.

for out/ref-style i prefer the signature of eg. TryParse: bool TryParse(out T result), as this gives a more natural way when using it eg. for:

int foo;
if (int.TryParse(someString, out foo)) {
   // do something with foo
}

whereas

MyState state;
Foo fooInstance = FooCreator.Create(out state);
if (fooInstance != null)
* OR *
if (state == State.Success)

may not be that natural


1

The main use for an out parameter is when you need to return more than one thing.

TryParse, a static method on plenty of numeric objects for example needs to return both a true/false when it succeeds and also the casted value.

Some people may prefer to return an object/structure which has multiple properties if you need to return multiple values; its just preference.


1

According to the C# documentation for out:

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed.

So, use a ref parameter when you need to pass a value in to the method, as well as receive a value from the method. Use an out parameter when the flow of information is only from the method to the caller. To complete the story there is the unadorned value parameter which passes information in to the method but cannot receive information back from the method.

I don't really buy the idea that out and ref are only to be used when you need to return more than one item from a method. I always prefer using out to return values from methods that have side-effects.

To me that's the answer to your question. Return a single value from a function through the function return value if the method does not have side-effects, and if the name of the method is a noun matching the meaning of the return value. Otherwise return values through out or ref parameters.

Linked


Related

Latest