0

I've got a problem. I know only how to use action and func, but the problem is that i need to put a method into a constructor like that.

Reader read = new Reader(1000, cki, method);

but the problem is that the method needs input like that.

public static void method(int Integer)

what do i do in that situation ?

Hui
  • 57
  • 1
  • 4

3 Answers3

2

You can use an Action<int> for the constructor parameter.The return type of Action is void and the generic argument is the parameter type.So it matches with your method which takes an int and returns void.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

You can't use a method, but you can use a Action

public Reader(int first, object cki, Action method)
{
    //ctor code here
    method.Invoke();
}

Than use:

var reader = new Reader(1000, cki, () => SomeMethod(123));
Darek
  • 4,687
  • 31
  • 47
  • What exactly are you trying to do? You can't pass a method. – Darek Mar 03 '15 at 13:01
  • yep i see Argument 3: cannot convert from 'method group' to 'System.Action' – Hui Mar 03 '15 at 13:03
  • is there another way ? – Hui Mar 03 '15 at 13:03
  • Why does it have to be a method? Theoretically, you could use Reflection and magic strings, but that would be awful and error prone. Could you update your question as to why does it have to be a method? – Darek Mar 03 '15 at 13:06
0

It seems you are looking for Action<int> and call it from withing the constructor like following?

using System;

public class Program
{
    public static void Main()
    {
        Sample s = new Sample((i) => {Console.WriteLine(i);});
    }
}

public class Sample
{
    public Sample(Action<int> method)
    {
        method(5);
    }
}
Jenish Rabadiya
  • 6,708
  • 6
  • 33
  • 62