I've got a class with almost 20 public properties. These properties have in common that they are all strings and they are filled with data from different tables of a database.
Additionally the set is pretty normal while the get is special as I need to call a specific method. This is done for each property at the moment (see below).
My question here is: Is there another more efficient way of doing this, thus a way where I don't have to define each public property by hand in this way?
class myclass { private string _Firstname; private string _Lastname; ..... public string Firstname { get { return ModifyStringMethod(this._Firstname); } set { this._Firstname = value; } } }
Like mentioned above every public property looks the same. The get calls ModifyStringMethod with the private member given as parameter while the set just sets the private member.
You cannot add a new property() to an instance at runtime, because properties are data descriptors. Instead you must dynamically create a new class, or overload __getattribute__ in order to process data descriptors on instances.
The collection of properties assigned to a class defines the class. A class can have multiple properties. For example, objects classified as computers have the following properties: Hardware ID, Manufacturer, Model, and Serial Number.
In c# properties, the get accessor will be invoked while reading the value of a property, and when we assign a new value to the property, then the set accessor will be invoked by using an argument that provides the new value.
You could try automatic code generation using T4 template. They are perfect when you have simple, repeating pattern of code and you are not expecting some cases to be slightly different from others.
Simply define a XML with list of property names and have T4 template generate partial class with each property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With