Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient way to define similar public properties

Tags:

c#

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.

like image 862
Thomas Avatar asked Apr 01 '15 12:04

Thomas


People also ask

How to add properties in Python?

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.

What are class properties?

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.

How do you call a property in C#?

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.


1 Answers

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.

like image 120
Euphoric Avatar answered Sep 21 '22 13:09

Euphoric