Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# – struggling with IDE0200/csharp_style_prefer_method_group_conversion

So came back to C# after several years. A lot has changed, still trying to recollect what I knew.

Using Visual Studio Pro Version 17.5.3. Created a new project and added Serilog for logging, but it wasn’t working properly, so I am looking at their debug doc – https://github.com/serilog/serilog/wiki/Debugging-and-Diagnostics. The first code line

Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));

Looks easy, passing a lambda to Enable. And this works as is if I open the project in vscode, when I dotnet build / dotnet run. Probably due to lack of auto-format configurations in vscode for now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But Visual Studio seems to be formatting this line and is breaking the build.

I have a "default" .editorconfig generated at the solution level, and there’s a rule in it – csharp_style_prefer_method_group_conversion = true:silent. This seems to be refactoring the lambda to become as

Serilog.Debugging.SelfLog.Enable(Debug.WriteLine);

(notice it’s removing the args, and then the build fails because

Severity    Code    Description Project File    Line    Suppression State
Error   CS1618  Cannot create delegate with 'System.Diagnostics.Debug.WriteLine(string?)' because it or a method it overrides has a Conditional attribute   Library C:\Users\user\Work\C#\Library\Logger\Logger.cs  13  Active

enter image description here

I silenced the rule in .editorconfig for now – changed it to false:silent, but looking/hoping to understand how to solve it.

Are there any benefits to using a C# method group if available?

csharp_style_prefer_method_group_conversion

>Solution :

If you will change it to Serilog.Debugging.SelfLog.Enable(Console.WriteLine); it will work. Problem here is that Debug.WriteLine will not be emitted by compiler in non-debug build (see the [Conditional("DEBUG")] attribute), so while the first version will become no-op (i.e. something like () => {}, compare release and debug output @sharplab.io) for the second one compiler will not be able to emit something.

Read more:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading