delegate parameter - can I do this?

  • Thread starter Thread starter Berryl Hesh
  • Start date Start date
B

Berryl Hesh

I am trying to eliminate duplicate logic in some loops, an example of which
is below

Both of the loops below are iterating over the same list. The thing that
varies is the method that counts different properties of the same class.
Each method has the same signature.

I am thinking I can have one count method that is passed a delegate for
either AppointmentCount() or ImplementationCount() but I don't know how to
set it up.

Thanks for your help!

public override int AppointmentCount() {
var total = 0;
foreach (var activity in ChildrenList)
total += activity.AppointmentCount();
return total;
}

public virtual int AppointmentCount() { return
_scheduledResourceAllocations.Count; }

public override int ImplementationCount() {
var total = 0;
foreach (var activity in ChildrenList)
total += activity.ImplementationCount();
return total;
}
public virtual int ImplementationCount() { return
_implementedResouceAllocations.Count; }
 
I am trying to eliminate duplicate logic in some loops, an example of which
is below

Both of the loops below are iterating over the same list. The thing that
varies is the method that counts different properties of the same class.
Each method has the same signature.

I am thinking I can have one count method that is passed a delegate for
either AppointmentCount() or ImplementationCount() but I don't know how to
set it up.

Thanks for your help!

public override int AppointmentCount() {
var total = 0;
foreach (var activity in ChildrenList)
total += activity.AppointmentCount();
return total;
}

public virtual int AppointmentCount() { return
_scheduledResourceAllocations.Count; }

public override int ImplementationCount() {
var total = 0;
foreach (var activity in ChildrenList)
total += activity.ImplementationCount();
return total;
}
public virtual int ImplementationCount() { return
_implementedResouceAllocations.Count; }

sure...

using System;

namespace ConsoleApplication33
{
class Program
{

static void Main ( string[] args )
{
Console.WriteLine ( Count ( Method1 ) );
Console.WriteLine ( Count ( Method2 ) );
}

static int Count ( Func<int> method )
{
return method ();
}

static int Method1 ()
{
Console.WriteLine ( "Method1" );
return 1;
}

static int Method2 ()
{
Console.WriteLine ( "Method2" );
return 2;
}
}
}

HTH
 
Back
Top