Delegate question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ^MisterJingo^

    #1

    Delegate question

    Hi all,

    I've been trying to get my head around delegates. The book i'm using
    had a single example, not much explaination, and didn't show how to set
    up a delegate and pass variables in and out of the functions it refers
    to. So I've been playing around and came up with he following code. I
    know it doesn't do much, but I just wanted to fit together delegates
    and parameter passing:

    //////////////// Code start

    public delegate int Sort(int a, int b, int c);

    public class SortProgram
    {
    public static int doSort(Sort ar, int a, int b, int c)
    {
    return(ar(a, b,c));
    }

    public static int highest(int first, int second, int third)
    {
    int tmp = 0;

    if (first > second)
    tmp = first;
    else
    tmp = second;

    if (tmp > third)
    return tmp;
    else
    return third;
    }

    public static int lowest(int first, int second, int third)
    {
    int tmp = 0;

    if (first < second)
    tmp = first;
    else
    tmp = second;

    if (tmp < third)
    return tmp;
    else
    return third;
    }

    public static int middle(int first, int second, int third)
    {
    int tmp = 0;

    if (first > second)
    tmp = first;
    else
    tmp = second;

    if (tmp > third)
    return third;
    else
    return second;
    }


    public static void Main()
    {
    int a = 90;
    int b = 110;
    int c = 300;
    Sort high = new Sort(highest);
    Sort low = new Sort(lowest);
    Sort mid = new Sort(middle);

    Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
    doSort(high, a, b, c));
    Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
    doSort(low, a, b, c));
    Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
    doSort(middle, a, b, c));
    }
    }

    //////////////// Code end

    Regarding the code, is this how one would go about using delegetes for
    such a function? Or am I doing something wrong / being long winded with
    my code?
    Is it ok to declare a delegete in the namespace (I figured other
    classes could use it if they needed to), or is it best to keep such
    declarations to class body?
    I gave up on events until I get my head around this, they're on my
    list next :).

    Any tips, or pointers would be welcomed.

    Chris

  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Delegate question

    MisterJingo,

    What you are doing is pretty much right. The only thing that I would
    think is excessive is the call to doSort. You don't need to wrap the
    delegate in a method call, you can just call the delegate directly.

    Other than that, it looks fine.

    The nature of the delegate will determine where I declare it. If I have
    a delegate which is specific to the class that will use it, then I will
    declare it in the class. However, for general event handlers (like
    EventHandler, for instance), I will declare that in a namespace.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - mvp@spam.guard. caspershouse.co m


    "^MisterJin go^" <misterjingo@gm ail.com> wrote in message
    news:1134565273 .593509.54680@g 49g2000cwa.goog legroups.com...[color=blue]
    > Hi all,
    >
    > I've been trying to get my head around delegates. The book i'm using
    > had a single example, not much explaination, and didn't show how to set
    > up a delegate and pass variables in and out of the functions it refers
    > to. So I've been playing around and came up with he following code. I
    > know it doesn't do much, but I just wanted to fit together delegates
    > and parameter passing:
    >
    > //////////////// Code start
    >
    > public delegate int Sort(int a, int b, int c);
    >
    > public class SortProgram
    > {
    > public static int doSort(Sort ar, int a, int b, int c)
    > {
    > return(ar(a, b,c));
    > }
    >
    > public static int highest(int first, int second, int third)
    > {
    > int tmp = 0;
    >
    > if (first > second)
    > tmp = first;
    > else
    > tmp = second;
    >
    > if (tmp > third)
    > return tmp;
    > else
    > return third;
    > }
    >
    > public static int lowest(int first, int second, int third)
    > {
    > int tmp = 0;
    >
    > if (first < second)
    > tmp = first;
    > else
    > tmp = second;
    >
    > if (tmp < third)
    > return tmp;
    > else
    > return third;
    > }
    >
    > public static int middle(int first, int second, int third)
    > {
    > int tmp = 0;
    >
    > if (first > second)
    > tmp = first;
    > else
    > tmp = second;
    >
    > if (tmp > third)
    > return third;
    > else
    > return second;
    > }
    >
    >
    > public static void Main()
    > {
    > int a = 90;
    > int b = 110;
    > int c = 300;
    > Sort high = new Sort(highest);
    > Sort low = new Sort(lowest);
    > Sort mid = new Sort(middle);
    >
    > Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
    > doSort(high, a, b, c));
    > Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
    > doSort(low, a, b, c));
    > Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
    > doSort(middle, a, b, c));
    > }
    > }
    >
    > //////////////// Code end
    >
    > Regarding the code, is this how one would go about using delegetes for
    > such a function? Or am I doing something wrong / being long winded with
    > my code?
    > Is it ok to declare a delegete in the namespace (I figured other
    > classes could use it if they needed to), or is it best to keep such
    > declarations to class body?
    > I gave up on events until I get my head around this, they're on my
    > list next :).
    >
    > Any tips, or pointers would be welcomed.
    >
    > Chris
    >[/color]


    Comment

    • Ignacio Machin \( .NET/ C# MVP \)

      #3
      Re: Delegate question

      Hi,


      Well the code use delegates correctly, you have a procedure from which you
      know the signature but that can be different implementations , you wait until
      runtime to select the correct alternative.
      Take a look at the Strategy pattern:



      cheers,

      --
      Ignacio Machin,
      ignacio.machin AT dot.state.fl.us
      Florida Department Of Transportation



      "^MisterJin go^" <misterjingo@gm ail.com> wrote in message
      news:1134565273 .593509.54680@g 49g2000cwa.goog legroups.com...[color=blue]
      > Hi all,
      >
      > I've been trying to get my head around delegates. The book i'm using
      > had a single example, not much explaination, and didn't show how to set
      > up a delegate and pass variables in and out of the functions it refers
      > to. So I've been playing around and came up with he following code. I
      > know it doesn't do much, but I just wanted to fit together delegates
      > and parameter passing:
      >
      > //////////////// Code start
      >
      > public delegate int Sort(int a, int b, int c);
      >
      > public class SortProgram
      > {
      > public static int doSort(Sort ar, int a, int b, int c)
      > {
      > return(ar(a, b,c));
      > }
      >
      > public static int highest(int first, int second, int third)
      > {
      > int tmp = 0;
      >
      > if (first > second)
      > tmp = first;
      > else
      > tmp = second;
      >
      > if (tmp > third)
      > return tmp;
      > else
      > return third;
      > }
      >
      > public static int lowest(int first, int second, int third)
      > {
      > int tmp = 0;
      >
      > if (first < second)
      > tmp = first;
      > else
      > tmp = second;
      >
      > if (tmp < third)
      > return tmp;
      > else
      > return third;
      > }
      >
      > public static int middle(int first, int second, int third)
      > {
      > int tmp = 0;
      >
      > if (first > second)
      > tmp = first;
      > else
      > tmp = second;
      >
      > if (tmp > third)
      > return third;
      > else
      > return second;
      > }
      >
      >
      > public static void Main()
      > {
      > int a = 90;
      > int b = 110;
      > int c = 300;
      > Sort high = new Sort(highest);
      > Sort low = new Sort(lowest);
      > Sort mid = new Sort(middle);
      >
      > Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
      > doSort(high, a, b, c));
      > Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
      > doSort(low, a, b, c));
      > Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
      > doSort(middle, a, b, c));
      > }
      > }
      >
      > //////////////// Code end
      >
      > Regarding the code, is this how one would go about using delegetes for
      > such a function? Or am I doing something wrong / being long winded with
      > my code?
      > Is it ok to declare a delegete in the namespace (I figured other
      > classes could use it if they needed to), or is it best to keep such
      > declarations to class body?
      > I gave up on events until I get my head around this, they're on my
      > list next :).
      >
      > Any tips, or pointers would be welcomed.
      >
      > Chris
      >[/color]


      Comment

      • Richard Grimes

        #4
        Re: Delegate question

        ^MisterJingo^ wrote:[color=blue]
        > I've been trying to get my head around delegates. The book i'm using
        > had a single example, not much explaination, and didn't show how to[/color]

        A delegate is a 'managed function pointer'. It can only be used to call
        managed methods (managed methods have a calling convention of clrcall).
        Unlike C function pointers, which allow you to cast a function pointer
        to any function, a delegate can only be used to call a method with the
        exact method prototype of the delegate.
        [color=blue]
        > set up a delegate and pass variables in and out of the functions it
        > refers to. So I've been playing around and came up with he following[/color]

        If you use C#, the compiler will allow you to call the delegate as if it
        is a method, so you just pass the method parameters to the delegate. If
        the delegate is to an instance method then the instance is passed to the
        constructor of the delegate when you create it.
        [color=blue]
        > public delegate int Sort(int a, int b, int c);
        >
        > public class SortProgram
        > {
        > public static int doSort(Sort ar, int a, int b, int c)
        > {
        > return(ar(a, b,c));[/color]

        yes, this is right.
        [color=blue]
        > public static int highest(int first, int second, int third);
        > public static int lowest(int first, int second, int third);
        > public static int middle(int first, int second, int third);[/color]
        [color=blue]
        > Sort high = new Sort(highest);
        > Sort low = new Sort(lowest);
        > Sort mid = new Sort(middle);
        >
        > Console.WriteLi ne("Select highest of {0}, {1}: {2}", a, b,
        > doSort(high, a, b, c));
        > Console.WriteLi ne("Select lowest of {0}, {1}: {2}", a, b,
        > doSort(low, a, b, c));
        > Console.WriteLi ne("Select middle of {0}, {1}: {2}", a, b,
        > doSort(middle, a, b, c));[/color]

        This is fine.
        [color=blue]
        > Regarding the code, is this how one would go about using delegetes for
        > such a function? Or am I doing something wrong / being long winded
        > with my code?[/color]

        It depends what you want to do, but what you have given is OK. Usually
        delegates are used to implement events. In general (but not in every
        case) the framework library classes use an interface reference when a
        method needs to have a parameter that is a pointer to a method, rather
        than using a delegate.

        An event is formalised metadata that describes the methods to add and
        remove delegates from an object. When the compiler sees the event
        keyword it generates a delegate field and methods to add and remove
        delegates to that field. The C# compiler will call these methods when
        you use the += and -= operators on the event member:

        delegate void CompleteDelegat e(string result);

        class Test
        {
        public event CompleteDelegat e Completed;
        public void DoSomething()
        {
        // do something
        if (Completed != null) Completed("fini shed");
        }
        }

        class Other
        {
        public static void CompletedStatic (string
        result){Console .WriteLine(resu lt);}
        public void CompletedInstan ce(string
        result){Console .WriteLine(resu lt);}
        }

        // Use it
        Test test = new Test();
        Other obj = new Other();
        // delegates can be combined...
        test.Completed += new CompleteDelegat e(Other.Complet edStatic);
        test.Completed += new CompleteDelegat e(obj.Completed Instance);
        test.DoSomethin g();
        [color=blue]
        > Is it ok to declare a delegete in the namespace (I figured other
        > classes could use it if they needed to), or is it best to keep such
        > declarations to class body?[/color]

        Again, its personal preference, I prefer them to be declared out side of
        the class. When the compiler sees a delegate it will create a delegate
        class.
        [color=blue]
        > I gave up on events until I get my head around this, they're on my
        > list next :).[/color]

        Easy, see above <g>.
        [color=blue]
        > Any tips, or pointers would be welcomed.[/color]

        The delegates above are called synchronously, that is, on the thread
        that invoked the delegate. You can also call delegates asynchronously,
        in which case the runtime will use a thread pool thread (you do not have
        to create this thread). You have to worry about the thread safety of
        your code/variables in the async case, you don't have to worry in the
        sync case.

        Richard
        --
        Fusion Tutorial: http://www.grimes.demon.co.uk/workshops/fusionWS.htm
        Security Tutorial:



        Comment

        • ^MisterJingo^

          #5
          Re: Delegate question

          Thanks for the replies all, they've helped a lot :).

          Chris

          Comment

          Working...