473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

C# Generics bug ? : Delegate can be used as Type in Generic Dictionary

<
note : this message was sparked in part by comments by David Browne on a
previous thread : "inserting an anonymous method as a value in a generic
dictionary ?" : David had shown the use of 'Delegate as a valid Type
declaration for the Value of a Generic Dictionary.
>
I am curious as to why I can compile and use this syntax : it seems to me to
violate the requirement that the Value of a Generic Dictionary be a Type
Name.

private delegate void theHandler();

private Dictionary<Control, theHandlertypeDict;

typeDict = new Dictionary<Control, theHandler>();

I now have a dictonary where the Key is of Type Control, and the Value of
the Key can be a named instance of theHandler :

theHandler theHandler1 = new theHandler(delegate {
MessageBox.Show("hello"); });

TreeView treeView1 = new TreeView();

typeDict.Add(treeView1, theHandler1);

typeDict[treeView1].DynamicInvoke();

Or I could can use an anonymous procedure inserted as a Value :

typeDict.Add
(
treeView1,
delegate
{
TreeNode currentNode = tv1.SelectedNode;
MessageBox.Show("treeview" + " " + currentNode.Text);
}
);

Jul 24 '06 #1
4 3371
Not sure what the problem is here... what did you expect? theHandler *is* a
type name (declaration); it is a class that derives from MulticaseDelegate
which derives from Delegate which derives from Object. I happily use
delegates in typed collections - on those occasions where I want a
collection of typed delegates!

What is the issue? Sorry if I have missed the point...

Marc

"Bill Woodruff" <bm****@dotscience.comwrote in message
news:uS**************@TK2MSFTNGP04.phx.gbl...
<
note : this message was sparked in part by comments by David Browne on
a previous thread : "inserting an anonymous method as a value in a generic
dictionary ?" : David had shown the use of 'Delegate as a valid Type
declaration for the Value of a Generic Dictionary.
>>

I am curious as to why I can compile and use this syntax : it seems to me
to violate the requirement that the Value of a Generic Dictionary be a
Type Name.

private delegate void theHandler();

private Dictionary<Control, theHandlertypeDict;

typeDict = new Dictionary<Control, theHandler>();

I now have a dictonary where the Key is of Type Control, and the Value of
the Key can be a named instance of theHandler :

theHandler theHandler1 = new theHandler(delegate {
MessageBox.Show("hello"); });

TreeView treeView1 = new TreeView();

typeDict.Add(treeView1, theHandler1);

typeDict[treeView1].DynamicInvoke();

Or I could can use an anonymous procedure inserted as a Value :

typeDict.Add
(
treeView1,
delegate
{
TreeNode currentNode = tv1.SelectedNode;
MessageBox.Show("treeview" + " " + currentNode.Text);
}
);



Jul 24 '06 #2
"Marc Gravell" wrote :
Not sure what the problem is here... what did you expect? theHandler *is*
a type name (declaration); it is a class that derives from
MulticaseDelegate which derives from Delegate which derives from Object. I
happily use delegates in typed collections - on those occasions where I
want a collection of typed delegates!

What is the issue? Sorry if I have missed the point...
.... original post by bw snipped for brevity ...

Marc, thanks for your response ! I posted this example because I was
puzzled by being able to do things this way.

I had always thought of a Delegate as a being more the declaration of a
"signature" of a future Method, rather than as a first-class Type.

While a declaration of the form :

Dictionary<Delegate, ObjecttheDictionary = new
Dictionary<Delegate, Object>();

Would have still raised questions in my mind, but would have been easily
acceptable, being able to do :

private delegate void theMethodBody;

Dictionary<theMethodBody, ObjecttheDictionary = new
Dictionary<theMethodBody, Object>();

Somehow seems intutively wrong. So I am just asking for some help in
understanding why this works.

As, so often, the problem being in my assumptions.

thanks, Bill Woodruff
Jul 24 '06 #3
I had always thought of a Delegate as a being more the declaration of a
"signature" of a future Method, rather than as a first-class Type.
It is both.
So I am just asking for some help in understanding why this works.
Actually, Dictionary<theMethodBody, Objectwould be a poor choice, as I'm
not sure how useful a delegate would be as a key, but that's irrelvant...
OK; "theMethodBody" here is the signature, but it also defines a type, with
an .Invoke method matching the signature provided by your
delegate-declaration. The key here is getting your head around
"theMethodBody" actually being a class declaration, similar to (not
correct):

public class theMethodBody : MulticastDelegate {
public Invoke(); // matches declares signature; note also Begin/End Invoke
// ctor is a little different to normal, so not included
}

Thus theMethodBody inherits all the features of MulticastDelegate, such as
GetInvocationList(), plus all those features of Delegate such as the
non-typesafe DynamicInvoke(); however, if you know you have a theMethodBody
instance you can use the type-safe Invoke(). All this is done at compile
time.

(As it happens, "theMethodBody" could be substituted for ThreadStart,
MethodInvoker, etc - as these match on signature. )

At runtime, we can create an instance of "theMethodBody"; as with .Net
generally, this delegate-instance is an object instance:
theMethodBody runMe = new theMethodBody(SomeSuitableMethod);
As you know, I can then invoke this either as runMe(), or runMe.Invoke();

Now suppose I want to run a number of methods (with equal signature) based
on the action a user has performed; then yes, I could have some uber-switch
statement, or I could use a Dictionary of typed-delegates:
Dictionary<int, theMethodBodyactions = new Dictionary<int,
theMethodBody>();
// fill
//blah
// user has selected an option; execute the matching code:
actions[selectedActionIndex].Invoke(); // lazy; no checking for existance
etc

It all "just works"; you could use a similar strategy to craft a bespoke
back-end storage for an event mechanism instead of a delegate instance with
+= and -= (although I'm at a loss for a good reason to do so). If this isn't
helping, I suggest reading up on delegates on MSDN.

Marc

"Bill Woodruff" <bm****@dotscience.comwrote in message
news:ui**************@TK2MSFTNGP05.phx.gbl...
"Marc Gravell" wrote :
>Not sure what the problem is here... what did you expect? theHandler *is*
a type name (declaration); it is a class that derives from
MulticaseDelegate which derives from Delegate which derives from Object.
I happily use delegates in typed collections - on those occasions where I
want a collection of typed delegates!

What is the issue? Sorry if I have missed the point...

... original post by bw snipped for brevity ...

Marc, thanks for your response ! I posted this example because I was
puzzled by being able to do things this way.

I had always thought of a Delegate as a being more the declaration of a
"signature" of a future Method, rather than as a first-class Type.

While a declaration of the form :

Dictionary<Delegate, ObjecttheDictionary = new
Dictionary<Delegate, Object>();

Would have still raised questions in my mind, but would have been easily
acceptable, being able to do :

private delegate void theMethodBody;

Dictionary<theMethodBody, ObjecttheDictionary = new
Dictionary<theMethodBody, Object>();

Somehow seems intutively wrong. So I am just asking for some help in
understanding why this works.

As, so often, the problem being in my assumptions.

thanks, Bill Woodruff

Jul 24 '06 #4
"Marc Gravell" <ma**********@gmail.comwrote in message news:uD**************@TK2MSFTNGP05.phx.gbl...
>I had always thought of a Delegate as a being more the declaration of a "signature" of a future Method, rather than as a
first-class Type.

It is both.
One way that might make it "look" better - since "theMethodBody" is acting as a type here, capitalize it:
TheMethodBody

Just a style thing, but it would help fit the concept.

--
Adam Clauss
Jul 24 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
16
by: bigtexan | last post by:
I would like to do the following and cannot figure it out. public class A<T> { public delegate T GetValueDelegate(A<T> var); public GetValueDelegate GetValue = new GetValueDelegate(B.GetValue);...
17
by: atgraham | last post by:
Here is the "lead C# architect" attempting to impugn C++ templates (bottom of the page). http://www.artima.com/intv/generics2.html (bottom of the page) (Full article begins at...
4
by: Cedric Rogers | last post by:
I wasn't sure if I could do this. I believe I am stretching the capability of what generics can do for me but here goes. I have a generic delegate defined as public delegate bool...
3
by: Showjumper | last post by:
Back in asp.net 1.1 i made custom collection classes per Karl Seguin's article On the Way to Mastering ASP.NET: Introducing Custom Entity Classes to take advantage of strongly typed data. Now with...
7
by: =?Utf-8?B?Q29kZVJhem9y?= | last post by:
Can someone explain a few things about collections to me. In C# 2 generics, you can create a collection class by inheriting from System.Collections.ObjectModel.Collection. Using this you can...
1
by: Bruce Wood | last post by:
I'm trying to "genericize" the following class. At the moment I have derived classes for each different type of event handler / event arguments, and I wanted to have a single, generic, catch-all...
8
by: ThunderMusic | last post by:
Hi, We need to serialize (binary) objects containing generic collections. The thing is, when we try to get the objects back (deserialize) with a different instance of the application, we receive...
1
by: =?Utf-8?B?TWFyaw==?= | last post by:
Hi... I'm a little perplexed by some of the generics collection stuff. Dictionary<Key, Valuebeing the rough equivalent of Hashtable, I was surprised to find there was no direct way to get to the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.