glasses-logo

<dominikgorecki> Web development on the Microsoft Stack <dominikgorecki>

C# Using the Out Method Parameter

Let’s say you need some method to perform some task and then return the value. The standard approach, of course, is to make the method return a value. What if you need the method to return multiple values? Or, better yet, you want to know whether the method succeeded in its task before you use the generated return? In this case, using the out method parameter becomes extremely useful.

Let’s say the project calls for creating a log-in method that returns the user’s GUID if it succeeds (not necessarily the best approach). If you do something like this:

public Guid login(User user)
{
...
}

You need to return an empty GUID if the log-in fails (or worse, a GUID specific for a failed log-ins). Then you have to perform some sort of logic to check if the  log-in succeeded. However, the method is the one that performs this test to begin with, which makes the test redundant; as well, it is ugly, unreadable, and not maintainable: what if it turns out that in the future empty.GUID is used for another use case, possibly an anonymous log-in. You should also consider that you are also enforcing an arbitrary rule in your code (ie, emptry GUID is a failed log-in). For a different case, what if the set of possible returnable values does not include in it an item that can stand for a fail.

A much better approach:

public bool login(User user, out Guid?)
{
...
}

This way, you have a clear indication whether the log-in succeeded or failed:

bool loginResult = login(user, out userGuid);

Or you can use it in your conditional statement:

if(login(user, out userGuid)
{... [DO SOMETHING WITH userGuid] ...}

References

MSDN – out parameter modifier (C# Reference)

7 Responses to “C# Using the Out Method Parameter”

  1. I like the article, and it is a good attempt. However, your syntaxing is incorrect on the code, which confuse your the uninitiated reader.

    public bool login(User user, out Guid?)
    {

    }

    You haven’t provided an identifier.
    You code should read
    public bool login(User user, out Guid? someName)
    {

    }

    You also need to declare a variable to pass in in order to get it out i.e

    Guid someName = null;

    if(login(user, out someName))
    {
    //Do something with someName
    }

    Other than that, I like the article, liked the style and tone you have used for it.

    Keep it up!

    • Dominik says:

      You are absolutely right. I wrote this from memory without the luxury of VS that I’m used to! I will fix the syntax as soon as I get a chance. Thanks for your input–much appreciated!

  2. Mystical Coder says:

    Out parameters are rarely a good idea, a better approach is to return a class which can contain multiple properties:

    public LoginResult Login(User user);

    public class LoginResult
    {
    public bool Successful { get; }
    public Guid UserId { get; }
    }

    • Dominik says:

      Hi Mystical Coder,

      I agree that the out method should be used sparingly and for simple implementations; I think I mention in the article that the typical log-in scenario is probably not the best time to use it. You are right that you probably would want to return an object that has what you need, but for something simple like int32.tryParse, is the perfect opportunity to use the out parameter. You wouldn’t want to implement the logic on the return in that case because it would be a little redundant. Let me know if you have any other reasons for not using it. If you have any references it would be much appreciated.

      Thanks for commenting!

      Cheers!
      D.

      • I kinda disagree with mystical coder. The approach he prescribes is also frought with danger! However, it does not necessarily make it a bad approach either. The keyword here is approach, like any features in a software development language, framework etc. what matters most is how the features are implemented.

        I see a valid case in the way Dominik has implemented and in fact I have done this myself in applications. An example here, is pass in a User Object(Class) and you may just need a an integer value of the roleID of that object, that property may not be on the User Object, and it may actually be derived by a call to a completely different function in another class. However, in a certain segment of your application you may need to validate the logged in user details and get the roleID. I see no harm, in writing a function that does this for me, you may argue that SRP, LKV etc.

        but the simple class could be

        public static class UserRole
        {
        public static void TryGetRoleID( User user, out int roleId)
        {
        //Implementation here

        //Check Login details

        //Get RoleID of Validated login

        }
        }

        }

        Now of course there are probably 1001 other approaches you can take to solve this exact problem, but that’s what makes software development such a great occupation, is that you are free to choose which one is best!

        • Dominik says:

          Well said Gary. There is definitely room for both approaches.

          The other benefit of using the out parameter is that a reference is passed back and you can create overloaded methods.

          This is especially useful when you want a similar method to output different parameters that are not nicely packaged in one class. Let’s say that at log-in you also count how many people are logged into each role. You wouldn’t want to keep that information in your LoginResult object which would be part of the page-life cycle, but you may want to update some object in the application life-cycle. This can be done very neatly with the out parameter without having to do it in the log-in method itself.

          Would you agree Gary? Or would you do it differently?

          • In principle I do agree with that.

            But then again we enter another approach of raising events! And the debate can continue for months about which approach is best :-)

            The important thing to take away here, is that a good developer should be familiar with all approaches, and select the best one for his particular problem. The key is to determine which approach leads to a code smell, or even code rot.

            What is good though is that at least you have developers talking :-)

Leave a Reply

Open Menu Button