resgh
resgh

Reputation: 984

Delegate as parameter in C# class constructor

Hi i have a class with a delegate as a parameter as shown in the code, but i get the errors Error 1 Type expected ...\Classes\Class1.cs 218 33 Classes and Error 2 ; expected ...\Classes\Class1.cs 218 96 Classes. How do i fix the issue? Thanks in advance! I'm trying to pass it byref so when a class initializes, some method of it is attached to the delegate.

public constructor(ref delegate bool delegatename(someparameters))
{
    some code
}

Upvotes: 3

Views: 22407

Answers (3)

The Mask
The Mask

Reputation: 17457

1 - Why you're using the ref keyword?

2 - the constructor is the class name? if not, you're doing this wrong, different of PHP: public function __construct( .. ) { } the constructor is named of class name, for example:

class foo { 
   public foo() { } // <- class constructor 
}

3 - Normally the types of delegates are void.

You're looking for this?

 class Foo {

        public delegate bool del(string foo);

        public Foo(del func) { //class constructor
                int i = 0;
                while(i != 10) {
                        func(i.ToString());
                        i++;
                }
        }
    }

Then:

class App
{

    static void Main(string[] args)
    {

        Foo foo = new Foo(delegate(string n) {
                            Console.WriteLine(n);
                            return true; //this is it unnecessary, you can use the `void` type instead.          });
        Console.ReadLine();
    }
}

The output:

1
2
3
4
5
6
7
8
9

Upvotes: 4

kprobst
kprobst

Reputation: 16651

You can pass something like Action<T> ... not sure why you want to pass it by reference though. For example, you can have a method like this one:

static void Foo(int x, Action<int> f) {
    f(x + 23);
}

And call it like this:

int x = 7;
Foo(x, p => { Console.WriteLine(p); } );

Upvotes: 5

DeCaf
DeCaf

Reputation: 6116

You cannot declare the delegate type in the constructor. You need to first declare the delegate type, and then you can use it in the constructor:

public delegate bool delegatename(someparameters);

public constructor(ref delegatename mydelegate)
{
   some code...
}

Upvotes: 5

Related Questions