In Foof We Trust: A Dialogue

User: The typeof(T) operator in C# essentially means “compiler, generate some code that gives me an object at runtime which represents the type you associate with the name T”. It would be nice to have similar operators that could take names of, say, methods and give you other metadata objects, like method infos, property infos, and so on. This would be a more pleasant syntax than passing ugly strings and types and binding flags to various Reflection APIs to get that information.

Eric: I agree, that would be a lovely sugar. This idea has been coming up during the C# design meeting for almost a decade now. We call the proposed operator “infoof”, since it would return arbitrary metadata info. We whimsically insist that it be pronounced “in-foof”, not “info-of”.

User: So implement it already, if you’ve been getting requests for the better part of ten years! What are you waiting for?

Eric: First, as I’ve discussed before on my blog, we have a very limited time and money budget for design, implementation, testing, documentation and maintenance, so we want to make sure we’re spending it on the highest-value features. This one has never made it over that bar.

Second, the feature seems at first glance to be simple, but in fact has a rather large “design surface” and would require adding a fair amount of new syntax to the language.

Third, it is nothing that you cannot do already with existing code; it’s not necessary, it’s just nice.

All these are enough “points against” the feature that it’s never made it into positive territory. It will stay on the list for hypothetical future versions of the language, but I would not expect it to ever happen.

User: Can you elaborate on some of the problems?

Eric: Let’s start with a simple one. Suppose you have infoof(Bar) where Bar is an overloaded method. Suppose there is a specific Bar that you want to get info for. This is an overload resolution problem. How do you tell the overload resolution algorithm which one to pick? The existing overload resolution algorithm requires either argument expressions or, at the very least, argument types.

Expressions seem problematic. Either they are evaluated unnecessarily, perhaps producing unwanted side effects, or you have a bunch of expressions in code that looks like a function call but isn’t actually. Either way is potentially confusing. So we’d want to stick with types.

User: Well then, it ought to be straightforward then. infoof(Bar(int, int)), done.

Eric: I notice that you’ve just introduced new syntax; nowhere in C# previously did we have a parenthesized, comma-separated list of types. But that’s not at all hard to parse.

You have some code in D that says infoof(Bar(int, int)). There are three candidates. Which do you pick?

User: Well, which would overload resolution pick if you called Bar(10, 10) ? Overload resolution tiebreaker rules say to pick the non-generic version when faced with this awful situation.

Eric: Great. Except that’s not the one I wanted. I wanted the method info of the second version. If your proposed syntax picks one of them then you need to give me a syntax to pick the others.

User: Hmm. It's hard because overload resolution actually gives you no way to force the call to go to one of the two “generic param” methods in this bizarre case, so some mechanism stronger than overload resolution needs to be invented if you want the feature to allow getting info of any method.

But this is a deliberately contrived corner case; just cut it. You don’t have to support this scenario.

Eric: And now you start to see how this always goes in the design meeting! It is very easy to design a feature that hits what initially looks like 80% of the cases. And then you discover that the other 80% of the cases are not covered, and the feature either takes 160% of its budget, or you end up with a confusing, inconsistent and weak feature, or, worse, both.

And how do we know what scenarios to cut? We have to design a feature that does something in every possible case, even if that something is an error. So we have to at least spend the time to consider every possible case during the design. There are a lot of weird cases to consider!

User: What are some of the other weird cases?

Eric: Just off the top of my head, here are a few. (1) How do you unambiguously specify that you want a method info of an specific explicit interface implementation? (2) What if overload resolution would have skipped a particular method because it is not accessible? It is legal to get method infos of methods that are not accessible; metadata is always public even if it describes private details. Should we make it impossible to get private metadata, making the feature weak, or should we make it possible, and make infoof use a subtly different overload resolution algorithm than the rest of C#? (3) How do you specify that you want the info of, say, an indexer setter, or a property getter, or an event handler adder?

There are lots more goofy edge cases.

User: I’m sure that we could come up with a syntax for all of those cases.

Eric: Sure. None of these problems are unsolvable. But they almost all require careful design and new syntax, and we would soon end up spending most of our design, implementation and testing budget on this trivial “sugar” feature, budget that we could be spending on more valuable features that solve real problems.

User: Well, how about you do the easy 80% and make “the other 80%” into error cases? Sure, the smaller feature is weaker and might be inconsistent, but something is better than nothing, and it’ll be cheaper to just do the easy ones.

Eric: That doesn’t actually make it cheaper a lot of the time. Any time we make a corner case into an error we need to carefully specify exactly what the error case is so that we can implement it correctly and test it confidently. Every error case still spends design, implementation and test budget that could have been spent elsewhere.

We would need to come up with a sensible error message, localize the error message into I don’t know how many languages, implement the code that detects the weird scenarios and gives the right error, test the error cases and document them. And we would need to deal with all the users who push back on each error case and request that it work for their specific scenario.

Trying to scope the feature down so that it is smaller adds work, and it is possible that it adds more work in the long run than simply making the larger version of the feature work in the first place. There are no cheap features.

User: Bummer. Because most of the time I really just want to get the method info of the method I’m currently running, for logging purposes during my test suites. It seems a shame to have to solve all these overload resolution problems just to get information about what’s happening at runtime.

Eric: Maybe you should have said that in the first place! The aptly named GetCurrentMethod method does that.

User: So what you’re telling me is no infoof?

Eric: It’s an awesome feature that pretty much everyone involved in the design process wishes we could do, but there are good practical reasons why we choose not to. If there comes a day when designing it and implementing it is the best way we could spend our limited budget, we’ll do it. Until then, use Reflection.

But Eric, there’s one really big advantage of typeof(name) vs GetType(“name”) … it’s checked at compile time. This also lets refactoring tools get in on the action. That’s a pretty big reason to go ahead and try to get infoof approved. I think there’d also be a significant performance delta (because typeof stores a metadata token, not strings and no runtime searching, right?)

Those are all good reasons to do the feature, yes. — Eric

Consider that one of the primary use cases can be expected to be white box testing — letting the test assembly access private members requires reflection, and it would be really nice if it could use a compile-time checked syntax and enable refactoring.

Yeah, the syntax may end up not being pretty in order to accommodate those edge cases, for the instance you mentioned you’d need something like:

infoof(C<T=int>.Bar(T,int))

But that’s still an awful lot more concise than chaining together calls to GetMethod with GetGenericTypeParameters, etc.

You can probably make your life easier by only searching for bare method names in the current class (where generics names are already in scope), not base classes. If you want a method from any other class then qualify it.

Of course, GetMethod and friends have some options — do you include static members or instance, public only or all visibilities, etc? How do you request the MethodInfo of a property’s getter vs the PropertyInfo? I wouldn’t want to have separate keywords for these so you’d need some syntax for patching them on:

Sure, it is better. But look at how much new syntax you just added to the language, for a feature that would get very little mainstream usage, compared to, say, auto props, or query comprehensions. Offer developers a pony and of course they say they want a pony; that’s unsurprising. My point is that if we give you the pony, then the unicorns we’d like to give you don’t fit into the budget anymore. — Eric

> Bummer. Because most of the time I really just want to get the method info of the method I’m currently running, for logging purposes during my test suites.

I think that may have been true (i.e. the most common case) before WPF shipped, but now? Every time I declare a new dependency property, I have to deal with stringified property names. Ditto for OnPropertyChange methods. A typo anywhere along the line, and a very subtle bug is introduced…

Frankly, I would be glad to have a "dumb" infoof that would require spelling out every single bit explicitly, with no overload resolution, implicit disambiguation etc ever taking place. E.g.:

infoof(int C.Bar) // instance property

infoof(static int C.Bar) // static property

infoof(void C.Blah(int, int)) // non-generic method taking two ints

infoof(void C.Blah<T>(T, T)) // generic method

infoof(void C.Blah<int>(int ,int)) // a specific instantiation of that same method

infoof(void C.Blah<int>(int ,int)) // a specific instantiation of that same method

infoof(void C<T>.Blah()) // method of an open generic type

infoof(void C<int>.Blah()) // method of a closed generic type

Wordy? Yes, sure, but it solves the "uncaught typo" problem, and doesn’t leave the room for ambiguities.

By the way, wasn’t "new" syntax for delegate instantiation in C# 1.0, before assignment was sugared for delegate lvalues and method groups, also lengthy for the same reason (to require the user to explicitly specify the delegate type, and therefore avoid the need to deal with overload resolution)?

> Given that the type of infoof(Thing) can already vary between PropertyInfo and MethodInfo, you could also allow it to be IEnumerable<MethodInfo> if the method name is overloaded.

When you use infoof(), you’d normally want to get one particular method. If you instead get a sequence, and still has to work with reflection methods on those MethodInfo objects to find the method you need (by argument count etc), you might as well just use reflection from the get go. For infoof() to be usable for scenarios where it’s desirable, it really needs to be able to unambiguously identify the specific method/property.

Point taken. But my point is that the resource-consuming mediocrity is the enemy of the awesome. Like I said before, how many free unicorns are you willing to give up in order to get this free pony? — Eric

> yes, but the remaining problems could then be solved with some extension methods defined on IEnumerable<MethodInfo>.

Not really – you open the same can of worms Eric described (e.g. how do you differentiate between Foo(int,int), and Foo<T=int>(T, T)?), you just move the problems from compiler to library space. But they don’t go away.

@Brad

> Perhaps the real solution to this problem isn’t infoof but something like a property delegate.

I don’t see how it would help for WPF dependency properties. A delegate for an instance property would require an instance (just as a delegate for a method property requires an instance) when constructed using language sugar, and not via reflection. And when you register WPF dependency properties, you do it in static initializers and/or ctor, so you don’t have that instance.

I no longer pine for infoof now that we have expression trees, but it does seem a little unfortunate that there are now many .NET projects out there with relatively similar chunks of code that inspect the expression tree and give you back the appropriate info instance. What would be nice is if the BCL team would add a small library to do this work. That way when you get people still complaining about the lack of infoof, you can point them to the library and be done with it.

"Like I said before, how many free unicorns are you willing to give up in order to get this free pony?"

I would have given up pretty much everything in .Net 4 for this. But that’s just me – I don’t use dynamic and all that, and I can’t stand string properties.

I agree with pminaev – this should be an extremely verbose feature, but it should exist. His syntax is pretty much what I thought of. You treat this feature as syntactic sugar, but there is no way to do this currently except string properties – which are the root of all evil because they are not compile-time checked.

</rant>

Off topic: Eric, what about that memoization post you promised two and a half months ago?

"…nowhere in C# previously did we have a parenthesized, comma-separated list of types. But that’s not at all hard to parse."

In fact, such a syntax DOES exist: Bar(int, int) is how you specify overload resolution in C# XML documentation, the parser for which is already part of csc. In fact, it is not at all clear to me why the XML doc overload resolver couldn’t be turned into infoof exactly as is; surely that would give us our 80% with minimal effort?

"But look at how much new syntax you just added to the language, for a feature that would get very little mainstream usage, compared to, say, auto props, or query comprehensions."

If you offered me a choice between either automatic properties and query comprehensions, or infoof, I would pick infoof without hesitation. Query comprehension syntax is nicer to read and write than method syntax in many cases, but not excessively so; and automatic properties are almost useless, especially in the presence of code snippets. Contrast that to infoof, which has NO alternative implementation (and NO, the runtime-evaluated expression tree tricks are nowhere near the same thing), but is critical for avoiding runtime failures when working with metadata, and surely the decision becomes obvious? And yet you and others continue to deprioritize a feature which has been more hotly requested by the community than any other that I have heard of. It is beyond maddening.

+1 to configurator’s comment. If C# 4 had NOTHING but infoof, I would consider that a worthy investment of the C# language team’s time.

Configurator and commongenius are overstating the matter. However, I would really like to see something like infoof. Even something simpler like nameof(foo.Bar) to aide in PropertyChanged and DependencyProperties would probably take care of 90% of the issues.

(Unless you fine C# guys have any better ideas to resolve these issues and the others mentioned in this thread?)

It also nicely handles the method overload resolution problem in a nice manner, all without adding additional language complexity.

The only problem with it is that it’s slow — depending on the types involved, I’ve seen it take anywhere from 1.5x – 5x slower than normal string-based Reflection. Acceptable? Maybe.

Fastest by far in my testing — faster than string-based Reflection, in fact — is Mike’s "Poor’s man infoof" using the Delegate.Method property. This effectively bypasses most of the Reflection infrastructure (no Type.GetMember(), etc.), and is the closest we can get to IL member lookup resolution.

The only problem with it is that it only works for methods, not properties. (It also shows how much C#’s type inferencing sucks, as if you have e.g. Lamba.Method<T>(Action<T>) and Lambda<T,R>(Func<T,R>) methods, and have a ‘static void Foo.Bar(int)’ func, Lambda.Method(Foo.Bar) fails to work, even though there’s only one method it can possibly match and I’d expect the parameter type to be inferrable. Here’s hoping that C#4 improves things…)

Observation: I think the real reason people want an infoof operator is that they don’t want to use reflection, even though what they’re asking for is available via reflection. That seems to stem from reflection being, well, confusing to use, and a little unwieldy. But like everyone else I write some unit tests, muddle through it, and when it works I have a gin and try to forget.

Given that, what is the real-world context most people want this stuff for? Enlighten me.

If anyone’s listening, I’d like a data access technology from MS that isn’t end-of-lifed after version 1.

Given that the guidance around reflection has, since day one, been "[bold]don’t use it[/bold] [fineprint]unless you really really have to[/fineprint]," it’s not surprising that people jump at any possible alternative to it. It’s awkward to use, error prone, and "slow" (which I’d guess for 90%+ of the cases it’s used isn’t an issue, but we all have this burning need to to make code "fast").

However, the .NET ecosystem has evolved quite a bit since 1.0, and we now live in a world of expression trees, dependency properties, code<->contract generation, ubiquitous unit tests, right-click refactoring, etc. etc. etc. Every one of those tools has a single shared requirement: metadata. Without it, they are useless, and as more and more tools leverage the power of metadata, it becomes more and more difficult to avoid reflection.

In short, the old guidance is showing its age. Sooner or later, metadata will have to become a first-class citizen, with easy access, compile-time sanity checks and a fast runtime path. Infoof may or may not be the solution that does that, but it’s hard to see the need diminishing.

I’m not sure why people see infoof as an ‘alternative’ to using reflection – given that we’d expect the resulting type of the expression to be a System.Reflection.MethodInfo, it’s more just a better way in to reflection than starting off with a string.

Basically, it comes down to the fact that typeof(Foo) turns into an IL ldtoken operation on the type metadata to get a runtime type handle, which is then resolved into a Type object by a call to Type.GetTypeFromHandle(), which is nice and quick. What we want is a clean way to compile code into the equivalent ldtoken to generate a RuntimeMethodHandle and have it resolved to a MethodInfo – something no library can accomplish, hence the pressure on the language and compiler team for a solution. That suggests a couple of things to me:

1) it should never return a PropertyInfo, only a MethodInfo – there being no such thing as a RuntimePropertyHandle. It should be possible to get hold of property getter or setter methods, of course.

2) it should be methodof not infoof (avoiding the confusing in-foof pronunciation that most people will read it as)

But 100% certain that I despise ANYTHING that requires me to use a string to represent information. The lack of compile time validation has probably caused more bugs (at least in "successful" builds, not necessarily in releases) than any other single factor since I have been programming in C#.

Because of this, our mandate for testing (which has to be manuaklly written) when using any feature that is string based, costs significant $$$ [we estimate $10-$25 per usage!!]

If anything can be done to provide alternatives which do not rely on strings, it would trump almost every other item on "my" backlog (including most of the 3.5 and 4.0 features]

Like Paul Batum said, why doesn’t the team set up an "infoof" project on codeplex, promote it and open it up to everyone to cover the accepted 80 % classes with the current syntax? this could help the team in also seeing where they’d need to focus their attention when this is discussed again…

Totally enjoyed the dialog driven format of this post. Definitely drives home the point. But the experience could have been enhanced by simply substituting “Booger” (aka Dudley Dawson), Mr Peabody, Beavis, or any other more palpable character in place of “User”. Maybe next time?

I confess that writing a dialogue about minor points of programming language design as a conversation between Beavis and Butt-head had not occurred to me; I encourage you to try the form yourself and report back how well it works. — Eric

I have been developing a library to help me generate type safe MSIL with Reflection.Emit, which define classes to wrap the various FooBuilder and FooInfo classes, and encapsulate calls to ILGenerator.Emit with the correct OpCode and validating that the types are consistent. And I have built an associated tool, that produces a library of static readonly properties to represent the members of a given class as objects from my library. Currently, the support for generics and private/protected members in this tool leaves much to be desired, and I find it is a hard problem to even define what the correct behavior is, even when the use case is only my personal use.

I previously mentioned some hypothetical C# fieldof and methodof operators, which would obtain FieldInfo and MethodInfo objects, in the same way that typeof retrieves Type at runtime. Eric Lippert explains the pros and cons of a combined infoof operator,

> it should never return a PropertyInfo, only a MethodInfo – there being no such thing as a RuntimePropertyHandle. It should be possible to get hold of property getter or setter methods, of course.

I think you’re putting the implementation before the usage scenarios. There are many cases where what we want is the property – in fact, I dare say that such cases would probably make the majority. If a feature would be implemented that does not achieve this, it’s next to useless, no matter how efficiently it’s implemented.

To be honest, I don’t care much about efficiency for such things anyway (they aren’t likely to be used in tight inner loops, or other scenarios where the hit would be noticeable). If it’s as slow as reflection, it’s fine by me. The only thing I really want is compile-time checking and type safety.

Now there are quite a few points where it can go wrong. We need to be sure that the string "Bar" actually matches the name of the property Bar; we need to make sure that registered type for the property matches the actual type; and we need to make sure that owner type is correct. All of these are not in any way checked statically. Furthermore, refactoring tools won’t catch them, either – if you rename Bar or change its type, you have to hunt all registered dependency properties manually, without help from auto-rename or "Find Usage".

I think it is quite "natural" that the design process for a feature supposed to give information about some existing language feature X reveals lots of corner cases if X itself has corner cases (like the "odious overloads" examples). In other words, the "infoof" design problems reveal design problems inside the space "of" refers to.

I think, it’s wrong to propose reflection as an alternative to “nameof” (or whatever you call it) and the example at the end of the story to be honest is not realistic.

Not realistic? Upon what data do you base that conclusion? Do you, like me, also get to see thousands of emails from C# users describing what features they’d like to see, and their real-world scenarios that drive those feature requests? Do you get input from focus groups? Do you get together with a few hundred MVPs once a year and talk to them about possible new features and how they’d use them? If you don’t do these things then how do you know what is “realistic” for the industry as a whole? — Eric

Why do I need “nameof” operator? Mostly just for two things.

First, to retrieve the name of the variables for assertions (how many ArgumentExceptions you throw in your code? how often you refactor your code?).

Next, for attributes. Current framework architecture requires to write method or property name as a string when it is needed to reference it in attribute. I’d like to see more checks in this area at complie-time due to possible refactorings, typos, etc. So, as for me something like

[ItemsSource(nameof(MyClass, Items))]

class MyCLass { public IList Items {get; } }

would be quite ok.

Will it be possible to use infoof in cases like this? Can it be used within existing framework infrastructure that requires compile time string input? I’m a little afraid that while trying to solve all the possible issues the feature will not be usable in the end.

The attribute case is one of the most common driving scenarios for this feature request. — Eric

If there was quite stupid “nameof” operator that just generated the compile time string from resolved item name or error in case of any ambiguities it would be much much more better than now when we deal with such errors in runtime.

Indeed, it is always easier to make a weak feature that doesn’t do anything difficult. The down side is that weak features still cost a lot, and you end up with a language full of weak features. — Eric

I’d far rather have more metaprogramming-like features such as expression trees than an improvement on reflection. I don’t see why people would want infoof over named and optional parameters and especially co- and contravariance. I have want for those features almost in every project, while I only felt the need to use reflection once or twice.

When I was talking about "not realistic" example I just meant that this feature is something different, e.g. there are several logging frameworks that write down caller name (via reflection, I don’t think infoof will help such frameworks) and it takes a few minutes to google the solution.

Of course it’s definitely better to specify attributes with say MethodInfo instead of method names but I was just wondering if infoof returns MethodInfo how can it be converted to string at compile time to coexist with the way things are done now (this is actually a week feature, it’s already there and we have to live with it). I believe you have the answer but from my point of view it’s a real challenge to combine these two worlds and I can only hope you found a way to do it.

“It is very easy to design a feature that hits what initially looks like 80% of the cases. And then you discover that the other 80% of the cases are not covered, “

How can both be 80%? Am I missing something here? It should be ‘80% of the cases, and then you discover that the other 20% of the cases are not covered’.

It’s a joke. You get through what you THINK are 80% of the cases, you’ve spent 80% of your budget on them, and then you discover that in fact you are only half done. In that scenario you are going to either ship a half-done feature, or you’re going to spend 160% of your budget. Hence the joke. — Eric

Indeed, as Sam’s blog notes, this is a case where what is allowed by the C# language and what is allowed by the CLR are different. We’re still trying to figure out what the right resolution is; until we do, I strongly recommend that you avoid situations like this. — Eric

@pminaev’s verbose option is pretty much what I’ve had in mind whenever I think about this feature because there are just so many edge cases. Even if some lightweight sugary syntax is provided for simple non-overloaded members, there needs to be an unambiguous specification available.

Even so some cases like explicit interface implementations would be tortuously difficult to specify and probably shouldn’t be supported at all since they just aren’t useful enough. Either that or we would need to provide syntax like: infoof(IEnumerator List<T>.(System.IEnumerable.GetEnumerator())) with some goofy parentheses to escape the explicit member name. But really?

That makes me wonder what the visibility rules should be… I imagine that for safety and consistency reasons we should use ordinary visibility rules governing member access in lexical scopes. In that case, references to explicit interface implementations are right out since we can’t even refer to the explicit members within their own implementation! (good riddance)

Obviously the syntax does need to support the keyword escaping mechanism: infoof(string MyType.@namespace) assuming we have a field called namespace. This presents no new challenges to the language.

Indexers are pretty easy: infoof(object MyType.Item[int]). Of course Item doesn’t appear in the C# language anywhere else so this leaks implementation details. So we could use infoof(object MyType.this[int]) I suppose. *cringe*

Another question is whether infoof should accept types or whether that should remain the domain of typeof. My intuition is to that infoof should only provide references to non-type members because otherwise we have an ambiguity in the case where a type T has a property called T. Using typeof(T) correctly resolves the type. Using infoof(object T.T) should get the property. If we provide a lightweight syntax for non-overloaded members, then infoof(T) should also get the property.

Constructors and finalizers aren’t hard: infoof(MyType(int)), infoof(~MyType()). It should be noted that the parentheses must not be omitted from constructor signatures.

As long as we use full names for everywhere then there isn’t much potential ambiguity. The problems start when we extend the syntax to allow specification of non-overloaded members with a short form name… so we might do well to just leave that option out!

Has anyone attempted to work out a full detailed proposal for infoof, its variations and ramifications? Would it be of use if someone in the community produced such a proposal?

Anyways, my main use-case driving this is for use in attributes but there are also quite a few cases, particularly for testing, where static binding to a member reference is required. Delegates and expression trees are cumbersome are of limited utility for some scenarios.

I do recognized that matter how this feature is scoped ‘infoof’ will be a lot of work for compiler and downstream tool writers. I know quite a few tools that will probably barf when presented with attributes that contain member tokens that are not types. I hope that someday a reasonable variation of this idea will appear in the language since it will greatly benefit static metaprogramming.

Of course, someday I’d also like to see the custom attribute blobs sprout the ability to express recursive data structures besides arrays similar to Java annotations. 🙂

What I’ve wished for many a time (and I don’t think I’m alone) is a nameof operator I can use with method arguments so as to populate the ArgumentException’s parameter in such a way that it is type-safe + refactor-safe. Getting full ParameterInfo metadata would be a bonus of course, but not required to be useful.

I struggle to think when nameof(argument) (or infoof(argument) for that matter) could ever have an edgecase associated with it, but I agree this would be (in your terms ) a ‘week’ feature in that it would only work within the scope of the method that has the arguments.

[in the rest of the world we call this incremental delivery: solve the easy problems first, and come back to the hard ones if you have time]

Note that a more general ‘nameof’ operator skips your overload resolution problem, since *it doesn’t do any* : you still need to pass the output from nameof to a reflection API *along with bindingflags, args etc…* to resolve to a method. It just saves you from littering your codebase with strings that you already put in the codebase once (as method/property/argument identifiers) and struggle to see why you should have to duplicate.

@piers7: if it does not do any overload resolution, how can it be refactoring-safe?

i.e., if there are several overloads, and one of them gets renamed, will the reference in nameof be renamed too?

I thought of a similar mechanism (in presence of several overloads, just return all of them, so methodof() would always return an array). same problem though. there is just no concept of referencing a name in C#, so anything would probaby be cumbersome.

as for the argument checks: 1) argument names have no runtime representation, so this would be an entirely different feature, and 2) how bad is this really? I believe a VS code snippet will solve this problem quite well. the argument name does not follow refactorings, but how often does such a mistake happen, and how often is this really a problem? (most of the times, it will still be clear which argument caused the problem, unless you actually swapped names)

@Eric

a few other ideas:

– explicit interface implementations: just don’t support them. you can use infoof to get the interface member straight from the interface and go from there.

– getting getters/setters and adders/removers: just let us have the PropertyInfo/EventInfo, they have methods to get to those values

– indexers and operators: pretty uninteresting. the kinds of operators are easily available, so they can be retreived using a library (MyUtil.GetIndexer (Type t)).

I would not consider an implementation that does not have any of those above weak.

– private members: just be consistent with typeof and disallow access

overloads and generics are tricky though, granted.

the problem is that if you don’t give us infoof, we’ll have to take care of overload resolution ourselves, on a library level. which is worse.

in any case I think the expression tricks used to extract MemberInfos from lambda-expressions would be good enough. the only problem here is that we cannot use them where we’d need them most: in attributes.

so I think I’ll give you the point about infoof and rather than keep on discussing stuff that is already decided, ask for a different one:

The funny part is that the first part of this request (generics) would actually be _really_ easy to implement, something that’s not supposed to be true for any language feature. (but that’s only because everything is already in place and you would just need to remove an unnecessary error check)

Anyway, thanks for the great explanation. I admit that I’ve been in the "how hard can it be" camp, but I don’t have any good answer to the generic overload question except "don’t support", but in this case I understand why you’d rather not do that.

@pminaev Eric wrote "(2) What if overload resolution would have skipped a particular method because it is not accessible? It is legal to get method infos of methods that are not accessible; metadata is always public even if it describes private details. Should we make it impossible to get private metadata, making the feature weak, or should we make it possible, and make infoof use a subtly different overload resolution algorithm than the rest of C#?"

I think in the context of the question the comment makes sense.

BTW, making infoof able to access members that would otherwise be unaccessible would be a dangerous feature anyway. there should not be any hard-coded references to private members of other assemblies in any case, and doing it via reflection wouldn’t make it any better. stuff is private for a reason. we should only access private members via reflection if they are dynamically discovered, as in a serializer.

At the same time I don’t see many use cases for statically getting a MethodInfo. Everything I can think of is ouputting the method name in messages (e.g. logging, or assertations).

For those scenarios GetCurrentMethod or a static aspect weaver like Post# can do wonders. And even if they break that’s not my code logic that’s breaking, just some outdated messages.

I think this pretty much rules out a methodof operator, and I am fine with this.

But please give the propertyof a chance.

You wrote that doing only part of the feature is "weak", but is it really? In that case typeof is "weak" but I’m sure you don’t want to remove it, do you?

1. propertyof is not so expensive. Properties are relatively easy to identify: propertyof(Length), or maybe propertyof(Array.Length) when outside the class. The only slightly tricky case is indexed properties, which are unsupported in C# anyway. So the worse case left is generic types… propertyof(List<T>.Count).

2. Ideally the compiler could infer from usage if propertyof should return a string (the property name) or a PropertyInfo instance.

3. This would be incredibly useful! Use cases are many. We currently must write property names as string at tons of places in the framework: attributes (e.g. ItemsSourceAttribute), INotifyPropertyChanged (very common those days), DependencyProperties registration, …

And you know what the problem with strings is. Say hello to runtime errors because of typos, and goodbye to safe refactoring, "Find all references", etc.

I personnally don’t think your argument to justify not implementing propertyof holds… regarding infoof in its genericity, sure. But in the particular propertof case, no.

How about we compromise, and get a way to generate a ldtoken instruction for the current method only?

Even better would be one that returns a RuntimeMethodHandle instead of a MethodBase, since I think the usual case is to pass it to some sort of diagnostic method that may only need to use it in rare cases where something is wrong and so in the normal case it may be able to skip the cost of constructing a MethodBase from a RuntimeMethodHandle (metadata loading, etc); but I can understand why, for consistency with the existing typeof keyword, which both ldtoken’s the RuntimeTypeHandle and creates a Type for it, it might be desirable just to have it always make the MethodBase.

Does your argument about "weak features" and having to document the error cases, not seem to apply neatly to the case of generic custom attributes? It is my understanding that the CLR understands custom attributes of generic types; only the C# compiler doesn’t. It seems to me that generic custom attributes should have been implemented according to your argumentation, because you claim the amount of effort in implementing, documenting and maintaing the error case is comparable to that of implementing, documenting and maintaing the working feature. How many people regularly request this feature, and what are the difficulties and downsides of implementing it?

Also, I notice one user has commented that they would like to be able to use infoof() in custom attributes. Since typeof() is allowed, this makes sense – it is in some sense a constant expression. But then why not simply allow expression trees and/or lambda expressions in custom attributes? They, too, are somewhat of a constant (in the sense that the compiler need not run any user code to evaluate it). Isn’t this another case of a similar nature as the above, where the amount of effort of supporting the feature would be comparable to not supporting it because it is an error condition? How many users regularly request the ability to specify a lambda expression or expression tree in a custom attribute, and what are the difficulties and downsides of implementing it?

"Observation: I think the real reason people want an infoof operator is that they don't want to use reflection, even though what they're asking for is available via reflection. That seems to stem from reflection being, well, confusing to use, and a little unwieldy. "

No. It's because it's a RUN TIME mechanism, when what is really needed is a COMPILE TIME one.

"Given that, what is the real-world context most people want this stuff for? Enlighten me."

The 99.9999% cases…

INotifyPropertyChanging/Changed and simple data binding.

And bottom line is that these functions are both needed, and should be used by forms designers and other tools.

Because their job should be to allow basic operations like data binding and change notification, in simple, standardised ways that

make refactoring easy

don't leave string names for properties littering the code,

don't require application programmers to be doing things to fix what is a combined shortcoming in the language and libraries,

don't incur yet more un-necessary runtime overhead in reflection,

and that are proper language-level or core library level and therefore don't have maybe six or seven different implementations of the same functionality lying around just because different library authors have chosen to solve it in different ways.

I wonder if WPF dependency properties would have used infoof(Stuff) instead of a static "StuffProperty" had it been available. Settings like one-way vs two-way would have been neatly described in attributes and everything would have been rosy and gorgeous.

I don’t understand the relevance of accessibility. typeof() is already limited to accessible types. Surely infoof() should, too. Anything else would make no sense in the context of the existing language.