Delegates and Reference Types

D

David Marsh

Hello,

I have a question about delegates and reference types. Given the followingcode:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace CSharpScratch
{
class Program
{

delegate void DelType(string message);

static void Main(string[] args)
{

DelType combined, d1, d2, d3;
d1 = delegate(string message) { Console.WriteLine(message + "!"); };
d2 = delegate(string message) { Console.WriteLine(message + "?"); };
d3 = delegate(string message) { Console.WriteLine(message + ".."); };


Console.WriteLine("===== By Themselves ======");
d1("Hello World");
d2("Hello World");
d3("Hello World");

Console.WriteLine("===== Combined ======");
combined = d1 + d2 + d3;
combined("hello");

Console.WriteLine("===== Combined 2 ======");
DelType combined2 = combined
combined2("hello");

Console.WriteLine("===== removal of d2 from combined2======");
Console.WriteLine("===== call d1 ======");
combined2 -= d2;
combined("hello");
Console.WriteLine("===== call d2 ======");
combined2("hello");

}
}
}

and the following output:
===== By Themselves ======
Hello World!
Hello World?
Hello World.
===== Combined ======
hello!
hello?
hello.
===== Combined 2 ======
hello!
hello?
hello.
===== removal of d2 from combined2 ======
===== call d1 ======
hello!
hello?
hello.
===== call d2 ======
hello!
hello.

I'm having trouble understanding why the 'combined' delegate contains all three methods at the end when I removed the d2 delegate from 'combined2'. This article (http://msdn.microsoft.com/en-us/library/900fyy8e.aspx) says that delegates are reference types. I would expect 'combined' and 'combined2' to be references to the same 'delegate' object.

Right now, it is acting like a value type. This appears to be the expectedbehavior, which is fine. It threw me for a loop that it would behave likethis despite being called a 'reference type'.

Have I misunderstood reference types? Are delegates a special case?

Any clarification would be greatly appreciated.

Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top