dotnet/roslyn

Proposal: Add optional warning for implicit runtime casts

Open

#14,382 opened on 2016年10月8日

GitHub で見る
 (3 comments) (3 reactions) (0 assignees)C# (4,257 forks)batch import
Area-Analyzershelp wanted

Repository metrics

Stars
 (20,414 stars)
PR merge metrics
 (平均マージ 6d 17h) (30d で 256 merged PRs)

説明

Version Used:

Visual Studio 15 Preview 4 (unsure of how to find what version of roslyn it uses).

Steps to Reproduce:

  1. Set warning level to 4 (maximum).

  2. Compile a program which has implicit casts such as the following:

    using System;
    using System.Linq;
    
    class Program
    {
        static void Main(string[] args)
        {
            // Implicit cast because var was not used.
            foreach (string thing in new object[] { 1, "asdf", 4, })
                Console.WriteLine(thing);
    
            // Implicit cast because the type was specified.
            var stuff = from string s in new object[] { "2", 4, "6", } select s;
            foreach (var thing in stuff)
                Console.WriteLine(thing);
        }
    }
    
  3. Observe that there are no warnings and yet runtime exceptions occur at each place where an implicit cast was used.

Expected Behavior:

I’d like to have compiler support in eliminating accidental usage of implicit casts from my codebase (e.g., something to pass to /warnaserror). These casts are not always obvious and they don’t always compile to runtime casts, but when they do they can result in errors that are not seen until runtime. One great strength of C# is its static typing. But if the language makes it so easy to accidentally write code that emits runtime casts, without even an optional warning, the compiler’s support for static typing is wasted.

I understand that a lot of people rely on these constructs to use legacy APIs which use non-generic collections. Thus I suggest that this new warning be made opt-in. I don’t know the best way to go about that though…

I’d like usage of the construct foreach («TypeName» item in collection) to emit this warning if it compiles to a runtime cast and for from «TypeName» item in collection select item to emit the same warning if it compiles to a call to Cast<«typeName»>(). Something like a message describing both the target and source types of the implicit cast:

Program.cs(9,18): warning CSXXXX: Specifying type results in a runtime cast from 'object' to 'string'. Consider using 'object' or 'var' instead.

Or for a more real-life example:

Program.cs(9,18): warning CSXXXX: Specifying type results in a runtime cast from 'IContainer' to 'Container'. Consider using 'IContainer' or 'var' instead.

Actual Behavior:

No warnings.

コントリビューターガイド