tags:

views:

48

answers:

1

Hi,

Instead of having an add() method in the repository, I would like to overload the += operator so that the expression

_repository += myModel;

will insert myModel into the database(after i submit changes)

I know that the objects of different type cannot be used in operator overloading. Still want to know if there is some alternate ways to accomplish this

Any help?

+1  A: 

I would strongly, strongly urge you not to do this even if you can. It goes against how operator overloading is meant to be used - what would you return from your operator? A new "clone" of the repository, or just this?

A generic method is the way to go here. Just say "no" to overusing operator overloading.

Jon Skeet
Ya, we have to return something here. But i want in such a way that myModel is just added to the datacontext, but return nothing which would be same as the Add() method. Just curious to know why the usage of operator overloading in this context is not encouraged
Veer
Because it's not obvious what it means. It might make sense for you (now..), but as you saw Jon didn't "get" what you expect this to do, what this does at all right away. It's a safe bet that your coworkers will agree and shake their head, wondering what's going on there.
Benjamin Podszun
The fact that you don't *want* to return anything but that the operator makes it act as `_repository = _repository + myModel` should be a good indication that it's not a good fit.
Jon Skeet
That's fine. One more question. Do you also say creating an indexer for the repository is a bad idea?(for retrieving the model using primary key)
Veer
Something like this: MyModel myModel = _repository[8]; instead of _repository.GetMyModel(8);
Veer
@Veer: If the repository *only* includes instances of MyModel, that makes sense. If it has different types, then you can't really do it easily.
Jon Skeet