2008-12-03

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

        {

            get

            {

                return new FontFamily("Segoe UI");

            }

        }