I was wondering if, in C#, one could pass an instance method as a delegate without an instance. For reference, this is possible in Java by doing example(InstanceClass::InstanceMethod)
. The compiler then turns this into the equivalent of a Func<InstanceClass, ReturnType>
which calls InstanceMethod()
on the provided InstanceClass
like so: item=>item.InstanceMethod()
. Is this possible in C# and if it is, how would one do it?
Edit: To clarify, I am asking how I can pass the method in C# without using a lambda expression. The Lambda expression given is an example of what the compiler would turn the call into. Just passing the method instead of using a Lambda expression would be useful if the method had many arguments
Edit 2: Here is an example to illustrate my question. Java:
class Instance{
public void InstanceMethod(){System.out.println("Hello World");}
public static void Example(){
ArrayList<Instance> list = new ArrayList<>(5);
list.add(new Instance());
list.forEach(Instance::InstanceMethod)
}
}
Output: Hello World
C#:
public class Instance{
public void InstanceMethod(){Console.WriteLine("Hello World");}
public static void ForEach<T>(this IEnumerable<T> input, Action<T> action){
foreach(T item in input){
action(item);
}
}
public static void Example(){
List<Instance> list = new ArrayList<>(5);
list.Add(new Instance());
list.ForEach(Instance.InstanceMethod);//error need instance to call method
}