0

I need to have the same attribute on properties of different classes, e.g. :

[Display( Name = "Last Name" )]

is there a way not to copy paste the same line on different classes/interfaces? instead have a construct that refers to that line and copy paste the reference everywhere instead?

jimjim
  • 2,414
  • 2
  • 26
  • 46

3 Answers3

1

You probably will find AOP helpfull. Search for best framework yourself.

Community
  • 1
  • 1
Ivan Bukashkin
  • 674
  • 3
  • 11
0

you could create a script in something simple like ruby or powershell to add in that line in the same place on every page, or to add it after a regex match. A simpler method would be to create a parent class and have every class you want to implement this attribute extend the parent class.

If you end up needing to make the same change in so many places that copy and pasting is too much work, then you should look at your project and try to decide if a relationship exists there or if there truly are that many unrelated fields that end up having the same value

Alexander Burke
  • 534
  • 7
  • 22
  • I don't need to make the changes in many places, many places need to refer to the same actual thing and not a copy of the thing. – jimjim Feb 07 '17 at 03:42
  • The same instance or the same property? If its the same instance then that sounds like a dependency that should be injected into everything relying on it. If its the same property then it likely should be a parent class that your other classes extend. You can make the property virtual if you feel you might need to override it in specific subclasses, but otherwise youll only need to set it up once – Alexander Burke Feb 07 '17 at 03:44
  • If using a parent class, make sure the attribute is [inheritable](https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited.aspx). – John Wu Feb 07 '17 at 03:48
0

I ended up using a constant instead:

[Display( Name = Constants.LastName )]

where Constants.LastName = "Last Name" ); is a defined string constant.

jimjim
  • 2,414
  • 2
  • 26
  • 46