Hi
I was wondering if it is possible, as my 5 minutes of experimentation proved fruitless.
I hoped it would be as easy as:
T Identity<T>(T t) { return t; }
But this fails to compile on generic methods taking Func parameters. Eg OrderBy. Even specifying type parameters (which is exactly what I want to avoid!), it fails to compile.
Next I tried something I thought would work:
Func<T, R> MakeIdentity<T, R>()
{
return (T t) => (R)(object)t;
}
Also no go :( (this compiles when applying type parameters, again, not what I want)
Has anyone had luck making such a thing?
UPDATE: please dont say: x => x, I know that, it's obvious! I am asking for a function, not an expression :)
UPDATE 2: When I refer to identity, I mean in the functional sense, where the function simply returns the same object that you passed to it. It is probably in every functional language I have come across, but those do not use static typing. I am wondering how to do this (if possible) with generics. Just for fun!
UPDATE 3: Here's a partial 'solution' based on the 2nd idea:
Expression<Func<T, T>> MakeIdentity<T>()
{
return t => t;
}
void Foo(string[] args)
{
var qargs = args.AsQueryable();
var q = qargs.OrderBy(MakeIdentity<string>());
...
}
I dont think anything more than this will be possible.