WPF applications and CA2104 rule

If you are using static fields such as:

 public static class Constants


        public static readonly FontFamily MyFontFamily  = new  FontFamily("Segoe UI");


with “{x:Static}” markup extensions such as:

FontFamily="{x:Static this:Constants.MyFontFamily  }"

you will get the following warning:

CA2104 : Microsoft.Security : Remove the read-only designation from 'Constants.MyFontFamily' or change the field to one that is an immutable reference type. If the reference type 'FontFamily' is, in fact, immutable, exclude this message.

If you remove the “readonly” modifier you get a different warning:

CA2211 : Microsoft.Usage : Consider making 'Constants.MyFontFamily' non-public or a constant.             

In order to solve the problem convert the field, to a property with get accessor only, such as:

public static FontFamily MyFontFamily




                return new FontFamily("Segoe UI");




Unknown said...

Great tip. This is one of the few FxCop rules that I couldn't figure out and your solution worked like a charm.

Anonymous said...

But a new FontFamily wil be created every time MyfontFamily is called.

Anonymous said...

very good!