Keyword function arguments in C#
November 9, 2016 Leave a comment
In this post we’ll quickly go through positional vs. keyword function arguments in C#.
Say you have the following function:
public string GetContent(bool base64encode, bool compress, bool withUniqueId, string filename, int maxSize) { return string.Empty; }
You’ll learn very early in your programming class that you can call a function by supplying the arguments in exactly the same order as they are listed in the method signature. Here’s an example:
string content = GetContent(true, false, true, "myfile.txt", 1000);
That’s perfectly fine and shouldn’t be any surprise to you. The supplied arguments are paired up with the required parameters of the function. “true” is assigned to “base64encode”, “false to “compress” and so on. This way of passing the arguments is called positional. If you mix up the position of each supplied argument then you’ll get a different result.
Keyword arguments
You can specifically state in the function call which value belongs to which argument. In this case you can even mix up the order in which the arguments are passed:
string content = GetContent(filename: "myfile.txt", withUniqueId: true, maxSize: 1000, base64encode: true, compress: false);
One advantage of keyword arguments is better documentation of your code. It will be easier for another programmer reviewing the code to understand which argument does what. Otherwise they may have to view the actual function code to see what the arguments mean: what’s “true”, what’s “false”, what do they stand for?
If you want to mix the two strategies then the positional arguments must come first:
string cont = GetContent(false, true, maxSize: 1000, withUniqueId: true, filename: "myfile.txt");
View all various C# language feature related posts here.