C# Programming > Miscellaneous

C# Generate Get Set Methods

C# get set generation

Generate Methods

To make coding in C# a little easier we can write a development tool to automatically generate C# get set methods. Manually coding get-set methods is usually a tedious task and generating the code automatically is not too complicated.

Keep in mind that there are a ton of ways to generate get-set methods in .NET. The way this development tool will do it is by reading a string that represents fields in a class and generate get set C# code to match it.

Class Fields

Most of the time a get-set method serves as a .NET class property, which means the underlying value of the property is a field. Our C# development tool is thus going to interpret lines of codes as fields and extract the appropriate data. For any given field, we only need to know the type of the variable and the name of the variable.

There are two ways in which fields are commonly defined:

[accessor] [type] [name] (private int myInt;)
[type] [name] (int myInt;)

For each of the two ways, programmers also might add initializing values to the fields. Since all we want is the name and type of the field, we can ignore the accessor (which is usually private anyway) and any initializing value (anything after the = sign).

One more thing to note is the name of the variable. It is common practice that C# private variables have an underscore (private int _myInt), when we generate the methods, it is better to remove the underscore.

Generating the Code

Generating the C# get-set methods has no special trick to it. For this development tool I opted to use StringBuilder since it makes it easy to generate large strings and makes the code easy to understand when appending one line at a time.

And as with get-set methods, sometimes programmers only want the property to be read, not modified, so a set accessor is not included. Given that this development tool is basic, you can set all generated properties to include only get or only set accessors or both. Even with that limitation, the development tool makes generating get-set methods in C# a lot more convenient.

Back to C# Article List