user3008254
user3008254

Reputation: 105

Multiple getter and setter

How to create multiple handler for getter and setter, not to write same code for every field. I understand that it has some design pattern for that.

public class TestClass
{
    private string _firstName;
    private string _lastName;
    private string _personDescription;
    private string _other;

    public TestClass() { }

    //same for lastName, personDescription, other
    public string FirstName
    {
        get
        {
            return _firstName;
        }
        set
        {
            _firstName = FixValue(value);
        }
    }

    private string FixValue(string value)
    {
        value = value.Trim();
        if (value == string.Empty)
        {
            return null;
        }

        return value;
    }
}

Upvotes: 0

Views: 3326

Answers (2)

Koryu
Koryu

Reputation: 1381

there is a default codesnippet called propfull, propg and prop (at least in visual studio 2010). but you still have to type the name and datatype. you can copy paste the snippet and modify it to call your custom method on set.

To autogenerate a property you can also rightclick on the variable, click on refactor then click encapsulate field. Enter propertyname or use default. click ok twice or enter.

Upvotes: 0

Jensen
Jensen

Reputation: 3538

One possible way of doing this is through Aspect Oriented Programming.

Basically, you create an aspect which defines custom functionality which is injected into your code at compile time.

An example of such a library is PostSharp. Take a look at the PostSharp tutorial Property and Field Interception.

In your case, you need to implement the OnSetValue method, where you can add your custom code. Then add the attribute you created above your property.

Upvotes: 3

Related Questions