Consider the following code, which provokes CA2104: Do not declare read only mutable reference types.
public class Test
{
// This provokes CA2104: "Do not declare read only mutable reference types".
protected readonly ImmutableClass ImmutableMember;
}
public class ImmutableClass
{
}
Does anyone know of a way to mark a class as immutable in a way that would suppress warning CA2104?
I tried decorating MutableClass
with [ImmutableObject(true)]
with no hope of success (since that attribute is pretty clearly for the Form Editor to use), and sure enough it doesn't work.
I assume that Code Analysis is using a list of known immutable types when determining whether to emit CA2104, so we can't use the same approach.
I guess that even if you could mark a class as immutable, there'd be no way for the compiler to actually check if it was true, but at least it could be a useful indicator.
Anyway, are there any attributes I'm overlooking? If not, suppression will have to do.
It seems that there is no alternative way to do this at the moment.
I did find an interesting blog from Joe Duffy (author of "Concurrent Programming On Windows") about this kind of thing.
He starts off with "Imagine we had an ImmutableAttribute."... :)
It's quite interesting - he went to the trouble of writing some new FxCop rules to do some analysis of types attributed as immutable.