Strong typing DisplayAttribute reference to Resources

Let’s say there is a decorated member with DisplayAttribute in code, i.e.:

public enum SomeEnum
{
	[Display(Name = "ResourceKey", ResourceType=typeof(Resource)]
	SomeValue
}

That’s all right except for one problem. If Name is mistyped or given resource key is latter changed then DisplayAttribute will point to an incorrect value and compiler won’t help. Resources designer doesn’t help as well, at least indirectly, because it doesn’t generate externally usable key names. It generates strong typed getters though, like:

internal static string ResourceKey {
        get {
             return ResourceManager.GetString("ResourceKey", resourceCulture);
        }
}

So, these getters are the only strong typed artifact that can be used to achieve strong typed reference. Luckily there is one C# (also VB) feature that was introduced in 6.0 and it is very useful in improving strong typed aspect of code. it is nameof keyword. it is evaluated at compile time and replaces the given expression with a string representation.

In other words, the sample above can be rewritten in strong typed manner:

public enum SomeEnum
{
	[Display(Name = nameof(Resources.ResourceKey), ResourceType=typeof(Resource)]
	SomeValue
}

This way the name is guaranteed to match since it is checked at compile time. So, no more mismatch between the key name and reference to it.

Of course, nameof can be used in many other places. Most notably in INotifyPropertyChanged/MVVM scenario.

Leave a Reply