Tuesday, March 11, 2014

named argument

About four minutes and fifty seconds into this we get the following example of using a named argument when assigning just one of several optional parameters when calling a method wherein the one of several is not necessarily the very first:

public class FileStream
{
   public FileStream (
         string path,
         FileMode mode,
         FileAccess access = FileAccess.ReadWrite,
         FileShare share = FileShare.Read,
         int bufferSize = 0x1000,
         FileOptions options = FileOptions.None)
   {
      
//Actual code
      new { path, mode, access, share, bufferSize, options }.Dump();
   }
}
 
void Main()
{
   new FileStream ("temp.txt", FileMode.Create,
         options: FileOptions.Asynchronous);
}

 
 

This trick came up last night while I was helping a friend understand someone else's code. A name followed by a colon followed by a value, as shown above in calling a method, is a "named argument."

No comments:

Post a Comment