Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic identity function for use with type inference

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.

like image 866
leppie Avatar asked Feb 19 '09 15:02

leppie


1 Answers

Type inference will not work since host method and input method both are generic. To do this you must write

myList.OrderBy<int, int>(Identity);

Or

myList.OrderBy((Func<int, int>)Identity);
like image 161
Chaowlert Chaisrichalermpol Avatar answered Oct 17 '22 19:10

Chaowlert Chaisrichalermpol