#272 – Differences Between ref and out Parameters

Ref and out parameters in C# are implemented in the same way, in the compiled code.  In both cases, a parameter is passed by reference, giving the method called a chance to change the underlying value.

ref and out parameters different purposes:

  • ref parameters are for input/output – a value is passed into a method and a new value is passed out
  • out parameters are for output – a value is passed out of a method

The compiler enforces the following rules:

  • ref parameters
    • A value must be assigned to parameter before method is called
    • Parameter may be referenced inside method before being written to
    • Parameter may be written to before returning from method
  • out parameters
    • A value may be assigned before method is called (but cannot be used inside method)
    • Parameter may not be referenced inside method before being written to
    • Parameter must be written to before returning from method
Advertisements

#267 – Passing Data Back from a Method Using out Parameters

If you want a method to return a single value, you can return that value as the result of the method.

        public int AgeInHumanYears()
        {
            return Age * 7;
        }

However, there might be times when you want to return more than one data item from a method.  You can do this with out parameters.  Putting the keyword out in front of a parameter tells the compiler that the caller will not pass data in, but the method will pass data out.

        public void GetDogVitals(out string fullName, out int age, out string barkPhrase)
        {
            fullName = string.Format("{0}, {1}", Name, Title);
            age = Age;
            barkPhrase = BarkPhrase;
        }

When you call the method, you also need to use the out keyword on the variables passed into the method.

            string hisFullName;
            int hisAge;
            string hisBark;
            kirby.GetDogVitals(out hisFullName, out hisAge, out hisBark);