Feb 28

Generic properties: you can’t do that!

Posted in Basics C# CLR      Comments Off on Generic properties: you can’t do that!

One of the things some people expect to be able to do is create generic properties. After all, properties will always generate getter and setter methods and nothing prevents you from creating generic methods. So why can’t I do something like this:

class Test{
    public T MyProp<T>{get;set;}

Well, it’s really a conceptual problem, you see…in theory, a property represents a characteristic of an object. Making it generic would mean that that characteristic would be able to change, but this really doesn’t play well with the theory, right? Anyway, what this means is that if you need to add some generic behavior into a class, then you  should do that by adding methods. Btw, don’t confuse the previous code with reusing the generic parameter defined by a class:

//compiles as expected :)
class Test<T>{
    public T MyProp{get;set;}   

In these last post, we’ve created a new generic type (we’ll come back to generics in the next posts)…notice that the type of the property isn’t  able to change after we create a new instance of a concrete type:

var test = new Test<Int32>();
test.MyProp = 10; //always int

I guess it’s time to say something about properties…to be honest, I really don’t like them. They look like fields, but they are methods. This means that some of the assumptions you end up doing when accessing fields aren’t true with properties. For instance, a field is always read/write (that might not happen with a property). Besides that, a property cannot be passed as a ref or out parameter and accessing one might also cause side effects (something which never happens with fields).

Over the years, I’ve seen them been abused by developers…hell, I’ve even abused them myself! Currently, I tend to stay away from them. In my opinion, people using them will end up with what is known as an anemic models (models in which there’s almost no behavior…). Currently, I only use properties in messages and for objects which are supposed  to feed UI forms (since the data binding process only works with them).

And that’s it for now. Stay tuned for more.