Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

delegate question

Status
Not open for further replies.

tzzdvd

Programmer
Aug 17, 2001
52
IT
Hi to all,
I have a question about the delegate
Example
Code:
public void delegate myDel();
public class myClass
{
   ...
   public myDel d;
}

public class Container
{
   List<myClass> lst = new List<myClass>();
   void AddFiveValues()
   {
      for (int i = 0; i < 5; i++)
      {
         myClass m = new myClass();
         m.d = new myDel(FunctionUsed); // <<<===
         lst.Add(m);
      }
   }

   void FunctionUsed()
   {
      ...
   }
}
This I think is a correct association of the delegate function.
Somewhere I have seen that is possible to use this sintax
Code:
m.d = FunctionUsed;
without the "new" statement.
I have tried it and I didn't receive any error or any runtime problem (apparently)
The reason, I think, is that the FunctionUsed matches the delegate structure

What is the difference between these two approach?

Thanks'

Davide

 
the delegate is just a contract signature. how it's fulfilled doesn't matter, only that the signature is the same.

once the delegate is defined you can invoke it with the proper parameters. example
Code:
private delegate string IntergerToString(int i);
private IntergerToString the_implementation;

private string explicit_implementation(int x)
{
   return x.ToString();
}

public void Convert()
{
   the_implementation = explicit_implementation;
   Console.WriteLine(the_implementation(1))
}
or you can use anonymous delegates
Code:
public void Convert()
{
   the_implementation = delegate(int a_number) {return a_number.ToString();};
   Console.WriteLine(the_implementation(1))
}
with .net 3.0 lamba expressions allow the syntax to be even shorter.
Code:
the_implementation = x=>x.ToString();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thanks Jason,
I know how the delegate functions.
My question is quite different.

I would like to understand the difference between
Code:
m.d = new myDel(FunctionUsed);
and
Code:
m.d = FunctionUsed;
assignment, in particular when the same function is assigned to multiple istance of a class.

Davide
 
oh. i would be interested in that too:)

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
interesting indeed. any luck from ildasm? i'll try digging tomorrow too; i don't have .net on my machine now.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top