How to specify the equivalent of /features:strict (of csc.exe) to msbuild.exe or in the .csproj file?

旧街凉风 提交于 2019-12-19 19:33:20

问题


Introduction

Consider this simple (and bad) C# class:

using System;

namespace N
{
  static class C
  {
    static void M(DateTime d)
    {
      if (d == null)
        Console.WriteLine("Yes");
      else
        Console.WriteLine("No");
    }

    static void L(object o)
    {
      if (o is Nullable)
        Console.WriteLine("Yes");
      else
        Console.WriteLine("No");
    }

  }
}

Both methods M and L have serious issues.

In M, we ask if a value of the non-nullable struct DateTime is equal to null via the lifted == operator (which exists since DateTime overloads operator ==). This is always falls, and the compiler can tell at compile-time, so we have a branch ("Yes") which is unreachable.

In N we ask if o is an instance of the static class Nullable which can never be the case (note, the static class Nullable is not the same as the struct Nullable<>). Again, this is a developer mistake, and the "Yes" statement is unreachable.

We do want a compile-time warning (or "warning as error") in these cases, right?

As it seems, through gradual accumulation of compiler errors and/or omissions in the old C# compiler that was used for C# 1.0 through 5.0, the expected compile-time warnings failed to appear with the old compiler. Luckily we have Roslyn/C# 6.0/Visual Studio 2015 now, and expect to get a warning. But no, because of the desire to not emit warnings from Roslyn that where not present with the old compiler (backwards compatibility?), these situations are still not warned against.

However, if you compile from the command line, with csc.exe, you can use:

csc.exe /features:strict ... ...

and you will get the warnings you want! /features:strict makes csc.exe include warnings that the old C# compiler "fogot".

My question

How do I specify the equivalent of /features:strict to msbuild.exe command line or in the .csproj file?

Sometimes, e.g. when we have XAML in our build project, it is not easy to use csc.exe directly, we have to use a .csproj file and compile through msbuild.exe.


回答1:


This flag is supported in csproj file directly, just add:

<Features>strict</Features>

To the appropriate PropertyGroup in your csproj file, and after build you will see this warning for your code:

Warning CS8073 The result of the expression is always 'false' since a value of type 'DateTime' is never equal to 'null' of type 'DateTime?'

If you want to do the same via msbuild command-line interface, just set this property with /p:Features=strict, like this:

/t:rebuild /p:Configuration=Debug /p:Platform=x64 /p:Features=strict


来源:https://stackoverflow.com/questions/37299549/how-to-specify-the-equivalent-of-featuresstrict-of-csc-exe-to-msbuild-exe-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!