views:

91

answers:

2

This question is related but not the same as this: http://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value

I love auto-properties, but sometimes I have to do something like this:

private string someName;

public string SomeName
{
    get
    {
       return someName;
    }

    set
    {
        someName = value.Trim();
    }
}

If I have to do the same thing many times, I start wishing that I did not need to type so many lines/characters of code. I want to be able to intercept the value and change it sort of like so:

public string Somename
{
    get;

    [Trim]
    set;
}

Is there a way to do something like this? Would it be stupid? Is there a better way? Any other general comments? I admit, the example I gave is a bit hypothetical and I cannot locate the exact code now which made me think of this.

Thanks.

+4  A: 

No there is not a way to do this. C# auto properties are meant to be syntactic sugar for only the most trivial of properties and nothing more.

JaredPar
+2  A: 

You can do it using AOP, like with Postsharp, but why aren't you just using a backing store in this case?

Also, for completeness, you should probably do this:

someName = (value ?? string.Empty).Trim();

to handle null as well.

Note that if you have a specific case in mind where there is more work involved, you should probably ask about that case, and not the trivial one you have in your question

Lasse V. Karlsen
Thanks, does Microsoft not provide its own solutions for Aspect Oriented Programming?
Hamish Grubijan
To a certain degree, with its ContextBound object, but it's not a very good solution for most AOP implementations. IL weavers are much better at it these days and can work with any type of object, whereas with the Microsoft method you'll have to inherit from a common class.
Lasse V. Karlsen
Wait, an "IL weaver" is something that expands syntactic sugar into different code? Is it akin `using <=> try/finally`, code contracts magic? I would think that a bug in an IL weaver would be somewhat hard to trace, as it might confuse the debugger.
Hamish Grubijan
Yes, that's what it does. It either at compile time or run time picks apart your IL, adds more code, then reassembles it. Typically though they modify the debugging information correspondingly, I've never had any problems with debugging with Postsharp. But yes, it's a risk you need to manage.
Lasse V. Karlsen