Func<void> as input parameter
Asked Answered
K

2

6

I have method in c# with some parameters:

public static void DeleteSingleItemInDataGrid
    (DataGrid dataGrid, String IDcolumnName, Func<int> afterCompletionMethod_ToRun)

I want to change third parameter type to Func< void > but I can't. how can I do it?

In other words my question is how can pass a method(or function with void result) as a method parameter?

Kepi answered 22/4, 2014 at 9:51 Comment(2)
use Action in steadSass
@LorentzVedeler Write that in an answer.Liquefacient
D
10

A delegate referencing a method that "returns" void is called an Action in .NET lingo, and that's what the delegate type is called as well:

So your method signature would be this:

public static void DeleteSingleItemInDataGrid
    (DataGrid dataGrid, String IDcolumnName, Action afterCompletionMethod_ToRun)

If you need to pass the int parameter to it, and not return int, it would be this:

public static void DeleteSingleItemInDataGrid
    (DataGrid dataGrid, String IDcolumnName, Action<int> afterCompletionMethod_ToRun)

This accepts a method taking an int parameter, that does not return anything (aka "returning" void).

This also means that you cannot create a generic method that accepts both methods returning something and methods not returning something with just one method, but need to create an overload using Action, and one using Func<T>.

Dupont answered 22/4, 2014 at 9:54 Comment(2)
I don't want to return int, I just need to return void. is there any way?Kepi
You can't "return void". A method declared as public void Test() must be sent via an Action.Dupont
F
1

The Action delegate you can use. It will perform given task and does not return a value.

Faction answered 22/4, 2014 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.