Click here to Skip to main content
15,880,905 members
Articles / Desktop Programming / WPF

Custom Getter Setters in C# using Regular Expression based templates

Rate me:
Please Sign up or sign in to vote.
4.89/5 (9 votes)
6 Sep 2014CPOL4 min read 48.1K   244   18   11
Quickly generate Getter Setters for a number of your properties in C# - using regular Expression based templates

Introduction

Here is a quick way to generate Getters, Setters in C# using Regular Expression based templates. Basically our input here is Key Value pairs separated by semicolon(;) - so this trick can be utilized to generate probably any templated text quickly as long as our input results in matches. By Key Value format (I mean format like [ PropertyName PropertyType; .... ] combinations).

Background

Many a times we want to bulk generate getter setters in Visual studio like Eclipse. And many times, we also want to add some additional functionality to our getter setters. We can use regular “prop”+TAB and “propfull”+TAB trick to generate full Properties with getter setters individually but we have less control over the template.

Like lets say we want null checking and also call the Notify method (as in case of wpf) in our setter:-

private string _Text;
public string Text
{
get { return _Text; }
set {
  if ( value != _Text)
    { _Text= value;
      RaisePropertyChanged("Text");
    }
  }
}

So what comes straight to mind is to write our own snippet and repeat use it in Visual studio. That’s one way to go.  We can do it using snippet designer. Just write a snippet and invoke our custom snippet the way we generally  invoke prop+TAB, propfull+TAB, ctor+TAB etc.

Moreover, what if we want to do it for a number of properties? Too much repetitive typing isn’t it? Let’s try to automate this.

What if I only want to type the PropertyType and PropertyName and I can generate rest of the getter setters (and I should have  a control over the template of code being generated).

Here comes Expresso to our rescue.  We’ll use Regular Expressions to match our properties and generate getter setters in bulk. Lets say I have these properties:

Guid _Id;
string _Text;
DateTime _CreateDt;
DateTime _LastUpdateDt;
bool _IsDeleted;

One thing I am sure is the structure of above combination is something like this:-

<PropertyType>+space+underscore+<PropertyName>+semicolon

Lets translate this into regular expression and find matches using Expresso.

In regular expression I'd say it as:-

(<a named group which matches a word>)+<one or more spaces>+<underscore>+(<another named group which matches a word)+semicolon   => this translates to

(?<PropType>\w+)\s+_(?<PropName>\w+);

In above Regular expression the \w matches a word. \s matches spaces. + means one or more occurances.  (_ and ; are as it is).

Using the code

Attached above (Zip File) is a Expresso project - it opens with Expresso (Its a Free App - links below). We can use app of our choice.

Basically our approach is very simple - we only need to paste three strings (1. Regular Expression), (2. Template) and of course (3. Input Text [PropertyType _PropertyName;] values). Below we will walk through the process to do it in Expresso itself.  Where to get Expresso and learn Regular Expressions is here:-

Once we download and install Expresso to our machine. Let us quickly walk through our code generation process here. Here’s how Expresso UI looks like. The basic functions of screen are annotated:-

  1. We write Expression in Regular Expression Block
  2. We Input the Sample Text or the input string to be parsed in Sample Text Block
  3. Then we press the Run Match to match the strings.

Expresso

We typed the following Regular expression and input fields to see the results in matches:-

  1. We typed Regular Expression 
    1. (?<PropType>\w+)\s+_(?<PropName>\w+);
  2. In Sample Text we typed our [ PropType _PropName; ] values with in regular syntax as below
  3. Clicking Match Shows us the results

Image 2

Next, we want to create our template for generating required code. So we will need to go to Design Mode tab and write our template there as below:-


  1. Go to “Design Mode”
  2. The Regular expression is same as we have recently tested above.
  3. Write our template using our named groups we have captured using our Regular Expression. The template is as below:
    private ${PropType} _${PropName};
    
    public ${PropType} ${PropName}
            {
                get { return _${PropName}; }
                set {
                    if (_${PropName} != value)
                    {
                        _${PropName}= value;
                        RaisePropertyChanged("${PropName}");
                    }
            }
  4. Press the Replace Button (the button with magnifier on blue page)

Image 3

Quite obvious of what I'm doing above. Just maneuvering the PropName and PropType named groups I have captured using my regular expression and filling in my template in between.

We click the replace and we get the getter setters there:-

Image 4

Points of Interest

Obviously we would want to learn about regular expression and here's a very good place to start:-


 

History

  • [05-Sep-2104]: Initial Post.
  • [06-Sep-2014]: Updated the expression & project to corrected one. Added links.
  • [07-Sep-2014]: Added Link to version 3.0 of Expresso (Its Free of Cost).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Singapore Singapore
I love programming, reading, and meditation. I like to explore management and productivity.

Comments and Discussions

 
QuestionHow is that an improvement. Pin
Dmitriy Krasnikov15-Sep-14 1:54
Dmitriy Krasnikov15-Sep-14 1:54 
AnswerRe: How is that an improvement. Pin
amitthk15-Sep-14 16:53
professionalamitthk15-Sep-14 16:53 
I understand and I already stated that the very first thing that comes to mind is custom snippet. However, perhaps you missed my assertion:-

- what if we want to do it for a number of properties? Too much repetitive typing isn’t it?

Let's say I am just writing a class with 25 new properties!!! So I go ahead and invoke the snippet one by one for each 25 properties isn't it? Isn't it fair to just pull a quick utility off pocket, white all those propertytype propertynames and get all my getter setters generated at once? If I want it for only one or two properties, I understand and I agreed to your statement absolutely stands true.

Moreover, this is not the only use case for above technique. I have used it to generate commands, even my MVVM ViewModels & Views using the same approach. Just because editing the regular expression is much quicker than invoking a snippet. And it generates in bulk - not for one at a time.

Oh I also used this to generate the SQL query from a list of e-mails which I was given and have to find records. I then generated the emails using templates as well.

I hope you see the point. This is just a quick trick applicable to general context and doesn't hurts learning! Thumbs Up | :thumbsup: Have a great day!
GeneralMy vote of 5 Pin
Malte Klena8-Sep-14 2:43
Malte Klena8-Sep-14 2:43 
GeneralRe: My vote of 5 Pin
amitthk8-Sep-14 16:23
professionalamitthk8-Sep-14 16:23 
GeneralMy vote of 5 Pin
Volynsky Alex7-Sep-14 10:40
professionalVolynsky Alex7-Sep-14 10:40 
GeneralRe: My vote of 5 Pin
amitthk7-Sep-14 22:30
professionalamitthk7-Sep-14 22:30 
GeneralRe: My vote of 5 Pin
Volynsky Alex8-Sep-14 9:28
professionalVolynsky Alex8-Sep-14 9:28 
QuestionTeeny improvement Pin
Roink6-Sep-14 6:33
professionalRoink6-Sep-14 6:33 
AnswerRe: Teeny improvement Pin
amitthk6-Sep-14 23:24
professionalamitthk6-Sep-14 23:24 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-Sep-14 20:44
Humayun Kabir Mamun5-Sep-14 20:44 
GeneralRe: My vote of 5 Pin
amitthk5-Sep-14 21:23
professionalamitthk5-Sep-14 21:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.