leora
leora

Reputation: 196479

What is the best way to pass an argument into a Func<> in C#?

I have the following code:

public void Test(Request request, Func<IEnumerable<Building>> buildings)
{
   vm.Buildings = Helper.GenerateDropdownList(request.BuildingId,() => buildings());
}

I now want to pass an additional argument to the buildings() callback

public void Test(Request request, Func<IEnumerable<Building>> buildings)
{
   var cityId = GetCity();
   vm.Buildings = Helper.GenerateDropdownList(request.BuildingId,() => buildings(cityId));
}

what is the right way to type that parameter?

Upvotes: 2

Views: 66

Answers (1)

user1914530
user1914530

Reputation:

Your buildings delegate will need to be a Func<T, TResult> instead of a Func<TResult>.

Assuming cityId is an int:

public void Test(Request request, Func<int, IEnumerable<Building>> buildings)
{
   var cityId = GetCity();
   m.Buildings = Helper.GenerateDropdownList(request.BuildingId,
                                             () => buildings(cityId));
}

Upvotes: 3

Related Questions