C
C#3y ago
nobody

Generics and type inference

public TDest MapTo<TSource, TDest>(TSource src)
{
var res = _mapper.Map<TSource, TDest>(src);
return res;
}
public TDest MapTo<TSource, TDest>(TSource src)
{
var res = _mapper.Map<TSource, TDest>(src);
return res;
}
Why can't the compiler infer my type of TSource? If I call that mehod I always have to specify it like this
Mapper.MapTo<ObjectA, ObjectB>(instance of ObjectA);
Mapper.MapTo<ObjectA, ObjectB>(instance of ObjectA);
It should be possible to call it just like this
Mapper.MapTo<ObjectB>(instance of ObjectA);
Mapper.MapTo<ObjectB>(instance of ObjectA);
I am just starting with .NET
8 Replies
Thinker
Thinker3y ago
There is no partial inference, you either have to specify all or no generic parameters. And yes this is annoying
nobody
nobodyOP3y ago
Oh that sucks I love using generics to simplify code, anyway thank you for your quick help!
Thinker
Thinker3y ago
np catsip language do you come from btw?
nobody
nobodyOP3y ago
@thinker227 I did most of my work with python/c++ and recently very much with Haskell (loving it) - whats your main language?
Thinker
Thinker3y ago
C# but also doing a bit of Haskell occasionally. Was just wondering what language you were using if you were expecting this kind of partial generic inference. C#'s type system is unfortunately nowhere as sophisticated as Haskell's or what you can do with C++ templates.
nobody
nobodyOP3y ago
Yeah its from my experiences with C++ templates and especially Haskell I just like working with strong typesystems. btw thats why Rust is simply awesome imho
Thinker
Thinker3y ago
Fair point Compared to a lot of other ones, C#'s type system is quite tame.
nobody
nobodyOP3y ago
True in comparsion, but its fine C# has some nice features too like record types which I've just learned about. I'm starting to try build up a github profile with some showcases thats why I try to learn different techs (webAPI in the C# case)
Want results from more Discord servers?
Add your server