Tag: C#

This post is continuation to last post,please go through last post if you didn’t went through.

In this post we shall see how to call a delegates with parameters and without parameter.

Lets declare delegate which doesn’t accept any parameters and one function.


//delegate
delegate void getnum();

//one simple function

void getnumber()
{
console.writeline("hi");
}

//now if we want to call delegate ,we should first declare a delegate instance
getnum g=new getnum(getnumber);
g.invoke(); //is same as g();

if you can see we had to pass method name in delegate instantiation and call invoke,which is same as

getnum g=getnumber;
g();

What if we use a function which has parameter..Lets see how to call delegate with this scenario..


delegate int transform(int x);

int square (int x)
{
return x*x;
}

//now to call delegate

transform t=new transform(square);
t(4);

Hope you got some idea on syntaxes of delegates.In next post what is the use of delegates.

Advertisements