Forcing named arguments in C#

It’s possible to force the callers to always use named args. I wouldn’t do this in most circumstances because it’s rather ugly, but it depends on how badly safe method usage is needed.

Here is the solution:

    int RegisterUser(
#if DEBUG
      int _ = 0,
#endif
      string nameFirst = null,
      string nameLast = null,
      string nameMiddle = null,
      string email = null) { /*...*/ }

The first parameter is a dummy that shouldn’t be used (and is compiled away in Release for efficiency). However, it ensures that all following parameters have to be named.

Valid usage is any combination of the named parameters:

    RegisterUser();
    RegisterUser(nameFirst: "Joe");
    RegisterUser(nameFirst: "Joe", nameLast: "Smith");
    RegisterUser(email: "joe.smith@example.com");

When attempting to use positional parameters, the code won’t compile.

Leave a Comment