Roslyn: Operator '?' cannot be applied to operand of type 'method group'

Created on 24 Jan 2017  路  8Comments  路  Source: dotnet/roslyn

Version Used: 2.0.0.61313

Steps to Reproduce:
C# int[] arr = { }; var count = arr?.Count;

Actual Behavior: Operator '?' cannot be applied to operand of type 'method group'

What is the method group here?

Area-Compilers Bug Concept-Diagnostic Clarity

Most helpful comment

Count is the method group (from IEnumerable<T>), arrays have Length.

All 8 comments

Count is the method group (from IEnumerable<T>), arrays have Length.

It seems to me that the error message is indeed confusing. Maybe something like this would be better?

Operator '?.' cannot be applied to operand 'Count' of type 'method group'

Notice that it now talks about ?. (not just ?) and also specifies that it's the Count part that is the issue.

Well it's only the ? that is underlined. What does it translate to so that Count is used as method group?

EDIT: I guess something like (arr == null) ? (int?)null : (int?)arr.Count; except that it can't figure out it should be int...
EDIT2: yes, so the method group is trying to be used as a return type... makes sense now at least :)
EDIT3: of course, and the ? is not the ? in code but the one in the cast type

@miloush method groups are a lie. Every place where you see a method group in C# is translated to a specific method reference in CIL. That's why you cannot have arr?.Count, which means "return Count is arr is null, otherwise return null". There's no Count that you can return.

You could argue that Func<int> count = arr?.Count; should work since Func<int> count = arr.Count; does, but it will never work with var, since there must be a way for the compiler to pick the correct method from the group.

Good point @orthoxerox with the Func.

My original scenario was actually int count = array?.Count ?? list.Count; so there were type hints but I understand where the error comes from now.

Isn't this closed?

It actually just int count = array?.Count() ?? list.Count; is it?

@Thaina I guess the idea is to make the error message actually say "array doesn't have a property or field named Count. Did you mean to write Count()?"

Or I guess if Count was underlined instead and the message remained the same, I wouldn't have complained either.

Was this page helpful?
0 / 5 - 0 ratings