Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Error CS1738 Named argument specifications must appear after all fixed arguments have been specified

Tags:

c#

public static Mutex CreateMutex(){
    MutexAccessRule rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
    MutexSecurity mutexSecurity = new MutexSecurity();
    mutexSecurity.AddAccessRule(rule);
    bool createdNew;
    return new Mutex(initiallyOwned: false,"Global\\E475CED9-78C4-44FC-A2A2-45E515A2436", out createdNew,mutexSecurity);
}

Error CS1738 Named argument specifications must appear after all fixed arguments have been specified

like image 511
Tâm Nguyễn Avatar asked Mar 04 '23 17:03

Tâm Nguyễn


2 Answers

So citing the C# Doc

Named arguments, when used with positional arguments, are valid as long

  • as they're not followed by any positional arguments

So this is the cause, why you are running into the compile error.

When using C# 7.2 and later it says:

Named arguments, when used with positional arguments, are valid as long

  • as they're used in the correct position.

For more information see: Named and Optional Arguments


So if we take a look at the constructor:

public Mutex (bool initiallyOwned,
              string name,
              out bool createdNew,
              System.Security.AccessControl.MutexSecurity mutexSecurity);

We will see that in your case the position is in the right order. And if you would switch to C# 7.2 or later your code will compile.

But for lower Version, you have two options:

  1. remove the argument naming for initiallyOwned
  2. use named arguments for all arguments

like:

return new Mutex(initiallyOwned: false,
                 name: "Global\E475CED9-78C4-44FC-A2A2-45E515A2436",
                 createdNew: out createdNew,
                 mutexSecurity: mutexSecurity); 

When using the second option the position of the named arguments does not matter anymore.

like image 58
Martin Backasch Avatar answered May 01 '23 05:05

Martin Backasch


I also came across this issue recently. The affected code was compiled in CI with an MsBuild 15 (~VS 2017) instead of MsBuild 16 (~VS 2019) which the developers in turn use locally.

With the same language setting (automatically chosen due to Framework 4.7.2) this resulted in CS1738 error in CI.

I upgraded the used MsBuild in the CI step instead of changing the code.

like image 21
tobster Avatar answered May 01 '23 05:05

tobster