2

I have the following class with an obviously uninitialized readonly field. This compiles fine with no erros or warnings:

public class Test
{
    readonly string s;

    public string GetString() => this.s.ToLower();
}

The fun part comes now. When I explicitly declare the field as private (which is default anyway, isn't it?) I now get a warning as I would expect:

public class Test
{
    private readonly string s;

    public string GetString() => this.s.ToLower();
}

warning CS0649: Field 'Test.s' is never assigned to, and will always have its default value null

Is this a Bug?

Iam using Microsoft Visual Studio Community 2019, Version 16.9.3.

codymanix
  • 28,510
  • 21
  • 92
  • 151
  • 3
    You can easily get a Microsoft programmer roll their eyeballs with Help > Send Feedback. – Hans Passant Apr 10 '21 at 22:36
  • Without testing, just guessing, what happens if you try to instantiate a `Test`? And what if you instantiate it with an initializer? `new Test() { s = "fnord" }` – Kevin Krumwiede Apr 10 '21 at 22:42
  • 1
    When all else fails, read the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers) – Nicholas Hunter Apr 10 '21 at 22:44
  • 2
    @NicholasHunter That's not really what the question is about. – Kevin Krumwiede Apr 10 '21 at 22:46
  • 1
    @NicholasHunter Or at most, it's related, but doesn't directly address the question. – Kevin Krumwiede Apr 10 '21 at 22:53
  • @KevinKrumwiede it addresses the question of what is the default access modifier of a field, which OP seems to think is relevant. – Nicholas Hunter Apr 10 '21 at 22:55
  • @NicholasHunter It's clearly relevant. The access modifier does alter the requirement to explicitly initialize a readonly field. The question is why, and exactly what are the rules? – Kevin Krumwiede Apr 10 '21 at 22:58
  • 1
    I also have Community 16.9.3 and I can confirm this behavior. – Kevin Krumwiede Apr 10 '21 at 23:01
  • ...and now I can't. When I changed your `GetString` method to a property `public string S => s;` it started telling me `s` was unused. Then, finally, it gave me the expected warning. This could be one of those things where VS loses its mind for a while and then corrects itself. – Kevin Krumwiede Apr 10 '21 at 23:10
  • The implicitly accessibility modifier is indeed `private`. This seems like a static analysis bug. – Aluan Haddad Apr 10 '21 at 23:59

0 Answers0