|Deep C# - Custom Attributes In C#|
|Written by Mike James|
|Friday, 19 March 2021|
Page 6 of 6
One solution would be to require the Formattable attribute to be applied to the entire struct before any of its fields are processed. That is, change the attribute to
add a constructor that takes no parameters and add a test that the passed-in parameter did indeed have a Formattable attribute before processing it.
The static method that implements the machinery would be better associated with the struct or, in general, the types to which it applies i.e. it should be a method of the type is is going to display the fields of. The extension method facility can be used to retrofit methods to classes that already exist. You can even add new methods to build in types such as int or string.
Unfortunately the problem is that structs inherit directly from ValueType makes it impossible to add an extension method to all structs and nothing else. You can easily add an extension method to a single named struct but why bother… you might as well just add the method to the struct directly. To add the display method to all value types you simple change its definition to:
That is, add the modifier “this” to the first parameter. Now you can call the display method using:
In other words, the display method has been added to every struct you create – powerful isn’t it!
Unfortunately it has actually been added to every value type so you can also write:
which is perhaps not what you intended. In this case it will display the two fields supported by a boxed int i.e. the maximum and minimum values.
Attributes are something that you probably won’t use everyday, but now that you know exactly how they work you can spot when the approach might be useful.
Buy Now From Amazon
or email your comment to: firstname.lastname@example.org
|Last Updated ( Friday, 19 March 2021 )|