Click here to Skip to main content
15,867,308 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 47.9K   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 
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 
You should have a direct link to the MOST RECENT Expresso application download, and mention that it's free. http://www.ultrapico.com/Expresso.htm[^]

Five stars! Smile | :)
Roink

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.