Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom attribute on parameter of an anonymous lambda

Tags:

c#

([MyCustomAttribute(...)] param1, param2) =>
{
    ...

where param1 is Type1 and param2 is Type2

It seems to me this is exactly the same as

private void method blah([MyCustomAttribute(...)] Type1 param1, Type2 param2)
{
    ...

But the first version is not allowed by the C# compiler. Why? Is this another one of those time vs effort/payback things? Isn't this just plain inconsistent?

like image 717
Ani Avatar asked May 15 '13 18:05

Ani


1 Answers

Why?

As I am fond of pointing out, the language design team does not have to provide a justification for not doing a feature. Rather, people who want features have to justify them.

If you were to ask a more targeted question instead of a vague "why?" you might ask:

If I were to pitch this feature to the C# design team, what problems would they identify with it?

There is no requirement in the C# language that lambdas be implemented as methods of a class at all.

First of all, they could be expression trees, in which case, what sense does it make to have an attribute there? And second, there is no requirement that a lambda be implemented as a method of a compiler-generated closure class, which means that there's no requirement that the parameter list even be something that you can sensibly put metadata on. Attributes are part of the metadata of the program, and one does not normally think of browsing compiler-generated types to consume their metadata as a sensible thing to do.

A strange but perfectly workable implementation of expression lambdas, for example, would be to generate the expression tree always, and then if it turned out to not be an expression tree lambda, generate a call to Compile out the other end. No metadata, so no place to put the attribute.

That would be strange, but the C# language has been carefully designed so that certain features like lambdas do not constrain the compiler writer to a particular implementation.

Is this another one of those time vs effort/payback things?

Yes.

Did someone think this though and say, naah !?

Not to my knowledge.

As I frequently point out, in order for a feature to be implemented it has to be thought of. To my knowledge you're the first person to ever think that an attribute on a lambda parameter is a good idea. Ideas that don't get thought of don't get designed, implemented, tested, documented or shipped.

Isn't this just plain inconsistent?

I suppose so.

like image 135
Eric Lippert Avatar answered Sep 21 '22 17:09

Eric Lippert