Home > Articles

This chapter is from the book

This chapter is from the book

Advanced Method Parameters

So far this chapter’s examples have returned data via the method return value. This section demonstrates how methods can return data via their method parameters and how a method may take a variable number of arguments.

Value Parameters

Arguments to method calls are usually passed by value, which means the value of the argument expression is copied into the target parameter. For example, in Listing 5.13, the value of each variable that Main() uses when calling Combine() will be copied into the parameters of the Combine() method. Output 5.5 shows the results of this listing.

Listing 5.13: Passing Variables by Value

class Program
{
  static void Main()
  {
      // ...
      string fullName;
      string driveLetter = "C:";
      string folderPath  = "Data";
      string fileName    = "index.html";

      fullName = Combine(driveLetter, folderPath, fileName);

      Console.WriteLine(fullName);
      // ...
  }
  static string Combine(
      string driveLetter, string folderPath, string fileName)
  {
      string path;
      path = string.Format("{1}{0}{2}{0}{3}",
          System.IO.Path.DirectorySeparatorChar,
          driveLetter, folderPath, fileName);
      return path;
  }
}

Output 5.5

C:\Data\index.html

Even if the Combine() method assigns null to driveLetter, folderPath, and fileName before returning, the corresponding variables within Main() will maintain their original values because the variables are copied when calling a method. When the call stack unwinds at the end of a call, the copied data is thrown away.

The value of a reference type variable is, as the name implies, a reference to the location where the data associated with the object is stored. How the runtime chooses to represent the value of a reference type variable is an implementation detail of the runtime; typically it is represented as the address of the memory location in which the object’s data is stored, but it need not be.

If a reference type variable is passed by value, the reference itself is copied from the caller to the method parameter. As a result, the target method cannot update the caller variable’s value, but it may update the data referred to by the reference.

Alternatively, if the method parameter is a value type, the value itself is copied into the parameter, and changing the parameter in the called method will not affect the original caller’s variable.

Reference Parameters (ref)

Consider Listing 5.14, which calls a function to swap two values, and Output 5.6, which shows the results.

Listing 5.14: Passing Variables by Reference

class Program
{
  static void Main()
  {
      // ...
      string first = "hello";
      string second = "goodbye";
      Swap(ref first, ref second);                                       

      Console.WriteLine(
          $@"first = ""{ first }"", second = ""{ second }""" );
      // ...
  }
  static void Swap(ref string x, ref string y)                           
  {
      string temp = x;
      x = y;
      y = temp;
  }
}

Output 5.6

first = "goodbye", second = "hello"

The values assigned to first and second are successfully switched. To do this, the variables are passed by reference. The obvious difference between the call to Swap() and Listing 5.13’s call to Combine() is the inclusion of the keyword ref in front of the parameter’s data type. This keyword changes the call such that the variables used as arguments are passed by reference, so the called method can update the original caller’s variables with new values.

When the called method specifies a parameter as ref, the caller is required to supply a variable, not a value, as an argument and to place ref in front of the variables passed. In so doing, the caller explicitly recognizes that the target method could reassign the values of the variables associated with any ref parameters it receives. Furthermore, it is necessary to initialize any local variables passed as ref because target methods could read data from ref parameters without first assigning them. In Listing 5.14, for example, temp is assigned the value of first, assuming that the variable passed in first was initialized by the caller. Effectively, a ref parameter is an alias for the variable passed. In other words, it is essentially giving a parameter name to an existing variable, rather than creating a new variable and copying the value of the argument into it.

Output Parameters (out)

As mentioned earlier, a variable used as a ref parameter must be assigned before it is passed to the called method, because the called method might read from the variable. The “swap” example given previously must read and write from both variables passed to it. However, it is often the case that a method that takes a reference to a variable intends to write to the variable but not to read from it. In such cases, clearly it could be safe to pass an uninitialized local variable by reference.

To achieve this, code needs to decorate parameter types with the keyword out. This is demonstrated in the TryGetPhoneButton() method in Listing 5.15, which returns the phone button corresponding to a character.

Listing 5.15: Passing Variables Out Only

class ConvertToPhoneNumber
{
  static int Main(string[] args)
  {
      if(args.Length == 0)
      {
          Console.WriteLine(
              "ConvertToPhoneNumber.exe <phrase>");
          Console.WriteLine(
              "'_' indicates no standard phone button");
          return 1;
      }
      foreach(string word in args)
      {
          foreach(char character in word)
          {
              if(TryGetPhoneButton(character, out char button))                          
              {
                  Console.Write(button);
              }
              else
              {
                  Console.Write('_');
              }
          }
      }
      Console.WriteLine();
      return 0;
  }
  static bool TryGetPhoneButton(char character, out char button)                          
  {
      bool success = true;
      switch( char.ToLower(character) )
      {
          case '1':
              button = '1';
              break;
          case '2': case 'a': case 'b': case 'c':
              button = '2';
              break;
          // ...
          case '-':
              button = '-';
              break;
          default:
                // Set the button to indicate an invalid value
                button = '_';
              success = false;
              break;
      }
      return success;
  }
}

Output 5.7 shows the results of Listing 5.15.

Output 5.7

>ConvertToPhoneNumber.exe CSharpIsGood
274277474663

In this example, the TryGetPhoneButton() method returns true if it can successfully determine the character’s corresponding phone button. The function also returns the corresponding button by using the button parameter, which is decorated with out.

An out parameter is functionally identical to a ref parameter; the only difference is which requirements the language enforces regarding how the aliased variable is read from and written to. Whenever a parameter is marked with out, the compiler checks that the parameter is set for all code paths within the method that return normally (i.e., the code paths that do not throw an exception). If, for example, the code does not assign button a value in some code path, the compiler will issue an error indicating that the code didn’t initialize button. Listing 5.15 assigns button to the underscore character because even though it cannot determine the correct phone button, it is still necessary to assign a value.

A common coding error when working with out parameters is to forget to declare the out variable before you use it. Starting with C# 7.0, it is possible to declare the out variable inline when invoking the function. Listing 5.15 uses this feature with the statement TryGetPhoneButton(character, out char button) without ever declaring the button variable beforehand. Prior to C# 7.0, it would be necessary to first declare the button variable and then invoke the function with TryGetPhoneButton(character, out button).

Another C# 7.0 feature is the ability to discard an out parameter entirely. If, for example, you simply wanted to know whether a character was a valid phone button but not actually return the numeric value, you could discard the button parameter using an underscore: TryGetPhoneButton(character, out _).

Prior to C# 7.0’s tuple syntax, a developer of a method might declare one or more out parameters to get around the restriction that a method may have only one return type; a method that needs to return two values can do so by returning one value normally, as the return value of the method, and a second value by writing it into an aliased variable passed as an out parameter. Although this pattern is both common and legal, there are usually better ways to achieve that aim. For example, if you are considering returning two or more values from a method and C# 7.0 is available, it is likely preferable to use C# 7.0 tuple syntax. Prior to that, consider writing two methods, one for each value, or still using the System.ValueTuple type but without C# 7.0 syntax.

Read-Only Pass by Reference (in)

In C# 7.2, support was added for passing a value type by reference that was read only. Rather than passing the value type to a function so that it could be changed, read-only pass by reference was added: It allows the value type to be passed by reference so that not only copy of the value type occurs but, in addition, the invoked method cannot change the value type. In other words, the purpose of the feature is to reduce the memory copied when passing a value while still identifying it as read only, thus improving the performance. This syntax is to add an in modifier to the parameter. For example:

int Method(in int number) { ... }

With the in modifier, any attempts to reassign number (number++, for example) will result in a compile error indicating that number is read only.

Return by Reference

Another C# 7.0 addition is support for returning a reference to a variable. Consider, for example, a function that returns the first pixel in an image that is associated with red-eye, as shown in Listing 5.16.

Listing 5.16: ref Return and ref Local Declaration

// Returning a reference
public static ref byte FindFirstRedEyePixel(byte[] image)                       
{
  // Do fancy image detection perhaps with machine learning
  for (int counter = 0; counter < image.Length; counter++)
  {
    if(image[counter] == (byte)ConsoleColor.Red)
    {
      return ref image[counter];
    }
  }
  throw new InvalidOperationException("No pixels are red.");
}
public static void Main()
{
  byte[] image = new byte[254];
  // Load image
  int index = new Random().Next(0, image.Length - 1);
  image[index] =
      (byte)ConsoleColor.Red;
  System.Console.WriteLine(
      $"image[{index}]={(ConsoleColor)image[index]}");
  // ...

  // Obtain a reference to the first red pixel                              
  ref byte redPixel = ref FindFirstRedEyePixel(image);                      
  // Update it to be Black                                                  
  redPixel = (byte)ConsoleColor.Black;                                      
  System.Console.WriteLine(
      $"image[{index}]={(ConsoleColor)image[redPixel]}");
}

By returning a reference to the variable, the caller is then able to update the pixel to a different color, as shown in the highlighted lines of Listing 5.16. Checking for the update via the array shows that the value is now black.

There are two important restrictions on return by reference, both due to object lifetime: (1) Object references shouldn’t be garbage collected while they’re still referenced, and (2) they shouldn’t consume memory when they no longer have any references. To enforce these restrictions, you can only return the following from a reference-returning function:

  • References to fields or array elements

  • Other reference-returning properties or functions

  • References that were passed in as parameters to the by-reference-returning function

For example, FindFirstRedEyePixel() returns a reference to an item in the image array, which was a parameter to the function. Similarly, if the image was stored as a field within the class, you could return the field by reference:

byte[] _Image;
public ref byte[] Image { get {  return ref _Image; } }

In addition, ref locals are initialized to refer to a particular variable and can’t be modified to refer to a different variable.

There are several return-by-reference characteristics of which to be cognizant:

  • If you’re returning a reference, you obviously must return it. This means, therefore, that in the example in Listing 5.16, even if no red-eye pixel exists, you still need to return a reference byte. The only workaround would be to throw an exception. In contrast, the by-reference parameter approach allows you to leave the parameter unchanged and return a bool indicating success. In many cases, this might be preferable.

  • When declaring a reference local variable, initialization is required. This involves assigning it a ref return from a function or a reference to a variable:

    ref string text;  // Error
  • Although it’s possible in C# 7.0 to declare a reference local variable, declaring a field of type ref isn’t allowed:

    class Thing { ref string _Text;  /* Error */ }
  • You can’t declare a by-reference type for an auto-implemented property:

    class Thing { ref string Text { get;set; }  /* Error */ }
  • Properties that return a reference are allowed:

    class Thing { string _Text = "Inigo Montoya";
    ref string Text { get { return ref _Text; } } }
  • A reference local variable can’t be initialized with a value (such as null or a constant). It must be assigned from a by-reference-returning member or a local variable, field, or array element:

    ref int number = 42;  // ERROR

Parameter Arrays (params)

In the examples so far, the number of arguments that must be passed has been fixed by the number of parameters declared in the target method declaration. However, sometimes it is convenient if the number of arguments may vary. Consider the Combine() method from Listing 5.13. In that method, you passed the drive letter, folder path, and filename. What if the path had more than one folder, and the caller wanted the method to join additional folders to form the full path? Perhaps the best option would be to pass an array of strings for the folders. However, this would make the calling code a little more complex, because it would be necessary to construct an array to pass as an argument.

To make it easier on the callers of such a method, C# provides a keyword that enables the number of arguments to vary in the calling code instead of being set by the target method. Before we discuss the method declaration, observe the calling code declared within Main(), as shown in Listing 5.17.

Listing 5.17: Passing a Variable Parameter List

using System;
using System.IO;
class PathEx
{
  static void Main()
  {
      string fullName;

      // ...

      // Call Combine() with four arguments                               
      fullName = Combine(                                                 
          Directory.GetCurrentDirectory(),                                
          "bin", "config", "index.html");                                 
      Console.WriteLine(fullName);

      // ...

      // Call Combine() with only three arguments                          
      fullName = Combine(                                                  
          Environment.SystemDirectory,                                     
          "Temp", "index.html");                                           
      Console.WriteLine(fullName);

      // ...

      // Call Combine() with an array                                      
      fullName = Combine(                                                  
          new string[] {                                                   
              "C:\\", "Data",                                              
              "HomeDir", "index.html"} );                                  
      Console.WriteLine(fullName);
      // ...
  }

  static string Combine(params string[] paths)                             
  {
      string result = string.Empty;
      foreach (string path in paths)
      {
          result = Path.Combine(result, path);
      }
      return result;
  }
}

Output 5.8 shows the results of Listing 5.17.

Output 5.8

C:\Data\mark\bin\config\index.html
C:\WINDOWS\system32\Temp\index.html
C:\Data\HomeDir\index.html

In the first call to Combine(), four arguments are specified. The second call contains only three arguments. In the final call, a single argument is passed using an array. In other words, the Combine() method takes a variable number of arguments—presented either as any number of string arguments separated by commas or as a single array of strings. The former syntax is called the expanded form of the method call, and the latter form is called the normal form.

To allow invocation using either form, the Combine() method does the following:

  1. Places params immediately before the last parameter in the method declaration

  2. Declares the last parameter as an array

With a parameter array declaration, it is possible to access each corresponding argument as a member of the params array. In the Combine() method implementation, you iterate over the elements of the paths array and call System.IO.Path.Combine(). This method automatically combines the parts of the path, appropriately using the platform-specific directory-separator character. Note that PathEx.Combine() is identical to Path.Combine(), except that PathEx.Combine() handles a variable number of parameters rather than simply two.

There are a few notable characteristics of the parameter array:

  • The parameter array is not necessarily the only parameter on a method.

  • The parameter array must be the last parameter in the method declaration. Since only the last parameter may be a parameter array, a method cannot have more than one parameter array.

  • The caller can specify zero arguments that correspond to the parameter array parameter, which will result in an array of zero items being passed as the parameter array.

  • Parameter arrays are type-safe: The arguments given must be compatible with the element type of the parameter array.

  • The caller can use an explicit array rather than a comma-separated list of arguments. The resulting CIL code is identical.

  • If the target method implementation requires a minimum number of parameters, those parameters should appear explicitly within the method declaration, forcing a compile error instead of relying on runtime error handling if required parameters are missing. For example, if you have a method that requires one or more integer arguments, declare the method as int Max(int first, params int[] operands) rather than as int Max(params int[] operands) so that at least one value is passed to Max().

Using a parameter array, you can pass a variable number of arguments of the same type into a method. The section “Method Overloading,” which appears later in this chapter, discusses a means of supporting a variable number of arguments that are not necessarily of the same type.

By the way, a path Combine() function is a contrived example since, in fact, System.IO.Path.Combine() is an existing function that is overloaded to support parameter arrays.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020