method-group

What is a method group in C#?

I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like : var list = new List<string>(); // ... snip list.Add(someObject.ToString); of course there was a typo in the last line because I forgot the round paranthesis after "ToString". The correct form would be : var list = new List<stri...

Convert Method Group to Expression

I'm trying to figure out of if there is a simple syntax for converting a Method Group to an expression. It seems easy enough with lambdas, but it doesn't translate to methods: Given public delegate int FuncIntInt(int x); all of the below are valid: Func<int, int> func1 = x => x; FuncIntInt del1 = x => x; Expression<Func<int, int>> f...

"<" operator error

Why is the ( i < UniqueWords.Count ) expression valid in the for loop, but returns "CS0019 Operator '<' cannot be applied to operands of type 'int' and 'method group'" error when placed in my if? They are both string arrays, previously declared. for (int i = 0;i<UniqueWords.Count;i++){ Occurrences[i] = Words.Where(x => x.Equals(Uni...

C# method group strangeness

I discovered something very strange that I'm hoping to better understand. var all = new List<int[]>{ new int[]{1,2,3}, new int[]{4,5,6}, new int[]{7,8,9} }; all.ForEach(n => n.ForEach(i => Console.WriteLine(i))); which can be rewritten as: ... all.ForEach(n => n.ForEach(C...

C# Language Design: method group inside `is` operator

I'm interesting in some design choices of C# language. There is a rule in C# spec that allows to use method groups as the expressions of is operator: class Foo { static void Main() { if (Main is Foo) Main(); } } Condition above is always false, as the specification says: 7.10.10 The is operator • If E is a method group or ...

Are there any benefits to using a C# method group if available?

When dealing with something like a List<string> you can write the following: list.ForEach(x => Console.WriteLine(x)); or you can use a method group to do the same operation: list.ForEach(Console.WriteLine); I prefer the second line of code because it looks cleaner to me, but are there any benefits to this? ...

Why does adding a return type prevent me from using method group syntax?

I'm trying to use a method group in a lambda expression, like this: public class Foo { public void Hello(string s) { } } void Test() { // this works as long as Hello has a void return type Func<Foo, Action<string>> a = foo => foo.Hello; } When I change the return type of Hello to int, however, I get 'Bar.Hello(string)' ha...