The CA2104 warning: Is there any way to mark a class as `Immutable` to suppress it?

倾然丶 夕夏残阳落幕 提交于 2019-12-01 15:21:56

A protected readonly field isn't really that clear. As protected, you might expect that a derived class can initialize the field:

public class Test
{
    protected readonly ImmutableClass ImmutableMember;
}

public class SpecialTest : Test
{
    public SpecialTest() { ImmutableMember = new ImmutableClass; }
}

But, that's not the case--you will get a compile error (CS0191).

I don't know the exact impetus behind CA2104, but you can get the same result without readonly via:

public class Test
{
    protected ImmutableClass ImmutableMember {get; private set;}

    public Test()
        :this(new ImmutableClasse())
    {
    }

    public Test(ImmutableClass immutableClass)
    {
        ImmutableMember = new ImmutableClasse();
    }
}

and avoid the CA2104.

Update:

w.r.t. to the comments (and to future readers), as you say you could use a backing field to get the read-only and provide a protected getter to get at it in derived classes:

public class Test
{
    private readonly ImmutableClass immutableMember;

    protected ImmutableClass ImmutableMember { get { return immutableMember; } }

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