views:

75

answers:

1

Hello, I have a question concerning a generic type parameter.

Let's say I have the following definitions in my domain model:

abstract class Entity<TId>
{
    public TId Id { get; private set; }
    /* ... */
}

class Person : Entity<long>
{
    public string Name { get; set; }
    /* ... */
}

Let's say now I want to create a method to view details of a person:

public void Details(long? id)
{
    if (!id.HasValue) {
        Error(...);
        return;
    }
    var person = PersonRepository.Get(id.Value);
    ShowPersonDetail(person);
}

Let's go further and say that PersonRepository is an specialization of Repository, so that its "Get" method is "automagically" implemented, to accept the correct strong-typed id argument (in this case, a long argument).


Now let's say one day I decide that Person's Ids should be Guids. What I want is to be able to change this ONLY in my Person class, and it will change everywhere else automatically. If I do so, in the code I have right now, the PersonRepository.Get() method won't need to be edited, but my Details() method will have to be changed.

I was looking for something like:

Details(Person.IdType id) { /*...*/ }

Oh, by the way, this "Details" method will be located in another assembly, if this might change anything...

but strongly-typed and it must accept either value types or reference types.

Any ideas?

Thanks!

+1  A: 

I'm not exactly sure if this is what you want. You can have the method take a Func<Person,T> and have it infer the types for you:

public T Get<T>(Func<Person,T> property) {
    return property(myPerson);
}

and call it with:

var id = PersonRepository.Get(p => p.Id);

The compiler is able to infer type of T from the lambda expression.

Mehrdad Afshari
It's not exactly that, the Repository part is ok, without funcs. The problem is for other methods, outside the scope of my domain model. I will try something with lambda expressions though. Thanks!
Bruno Reis