Before reading any further, please read the disclaimer in the C# Bloopers post.
When you declare a member variable, and then you try to read it from within the constructor without having first initialized it, you receive no warning about accessing an uninitialized member. This happens even if the member is declared as readonly.
namespace Test2
{
public class Test
{
public readonly string m;
public string n;
protected readonly string o;
protected string p;
private readonly string q;
private string r;
Test()
{
m.ToUpper(); //Blooper: no warning about accessing uninitialized member.
n.ToUpper(); //Blooper: no warning about accessing uninitialized member.
o.ToUpper(); //Blooper: no warning about accessing uninitialized member.
p.ToUpper(); //Blooper: no warning about accessing uninitialized member.
q.ToUpper(); //Blooper: no warning about accessing uninitialized member.
r.ToUpper(); //Blooper: no warning about accessing uninitialized member.
q = "q"; //to prevent Warning CS0649: Field is never assigned to, and will always have its default value null
r = "r"; //to prevent Warning CS0649: Field is never assigned to, and will always have its default value null
}
}
}
Someone might argue that this is behavior is fine because the member in question is guaranteed to contain its default value. First of all, a readonly member containing its default value is completely useless. (See C# Blooper №1: No warnings about uninitialized readonly members) Secondly, if the compiler is to help the developer catch potential errors and write better code, this is not a valid excuse: a different strategy is necessary.
Read more »