Question

I want to apply this:

private string _name;

public string name
{
    get { return _name; }
    set { _name = Fix(value); }
}

to all string the members of a class, and don't want to repeat the same code for all the class members.

An obvious solution would be to put that code on a class to handle the problem and declare all string members as: myString instead of string, however that would mean that I would have to access the main class members like this: email.fixed instead of just email.

So I was wondering, is there is some kind of template I can define and then apply easily?

No correct solution

OTHER TIPS

You could create a Code Snippet for Visual Studio to handle building a property this way.

MSDN includes documentation on Creating a Code Snippet, which can include replacement parameters (the name).

You might want to research Aspect Oriented Programming, which allows you to easily do things like this.

http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS

Create a type with an implicit conversion to and from string:

public class FixedString
{
    private string str;
    public FixedString(string str){this.str = str;}
    public static implicit operator FixedString(string str)
    {
        return new FixedString(Fix(str));
    }
    public static implicit operator string(FixedString fixed)
    {
        return fixed.str;
    }
}

You can now create a property of this type, but treat it as if it's a string.

Create a regex replace and use Visual Studio's (v2012/2013) find and replace regex functionality.

For example let us say you have a field like this to change into a property

public string Name;

and you want to change it to have a backing field and the setter you desire.

private string _Name;

public string Name 
{
   get { return _Name; }
   set { _Name = Fix(value); }
}

The find /replace regex pattern in Visual Studio to find is this

public\s+string\s([^;]+);

the replace pattern (with appropriate line spacings and tabs) is this

private string _$1;\r\n\r\n\tpublic string $1\r\n\t{\r\n\t\tget\r\n\t\t\t{ return _$1; }\r\n\t\tset\r\n\t\t\t{\r\n\t\t\t\t_$1 = Fix(value);\r\n\t\t\t}\r\n\t\t}

Then step through the finds and do a replace as needed within your class.

I have done similar to add INotifyChange method calls on blank properties created after doing the code snippet <tab><tab>prop action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top