Dave wrote:
I've got these declarations:
public delegate void FormDisplayResultsDelegate<Type>(Type
displayResultsValue);
public FormDisplayResultsDelegate<stringdisplayMsgDelegat e;
instantiation:
displayMsgDelegate = DisplayStatusMessage;
implementation:
public void DisplayStatusMessage(string statusMessage)
{
StatusTextBox.Text = statusMessage;
}
however, the following seems more proper to me and also works:
public void DisplayStatusMessage<Type>(Type statusMessage)
{
StatusTextBox.Text = statusMessage.ToString();
}
can anyone explain what's happening under the covers please?
(implicit casting i guess?...)
Can you post the code in which the second method declaration "works"?
How are you using the method? As an alternative to declaring the
delegate at all? Or are you somehow using an instance of the generic
method to initialize the delegate variable?
I can see why it would work in some cases but if you, for example, used
"int" instead of "string" as the Type parameter for the generic method,
it wouldn't. That is, you wouldn't be able to assign that concrete
instance of the generic method to the concrete "string"-based delegate type.
I'm not sure why the generic method seems more proper to you, but the
basic reason it works is that the method signature that results matches
the signature required by the delegate. A generic method can only be
used with a concrete instance of that method, and once you create that
concrete instance, it's just like any other method, with a signature
that looks just like any other method.
So as long as you create a concrete instance of your generic method that
has the same signature required by the delegate, you can use it.
However, that's not to say that's necessarily a useful way to use a
generic method. A generic method has the same basic purpose as generic
types; that is, it allows you to declare a method that can be used with
a wide variety of types without knowing the type in advance. However,
in your example, there's not necessarily anything about your method that
takes advantage of being generic.
Without knowing exactly what you're trying to do, it's hard to say which
is "better". If you really want a generic method to go along with the
generic delegate type, then I'd say the generic method is better. But
from only the code you posted, it's not really obvious why generics are
being used at all. And if generics are desirable, it may be that you
have a design where you need a specific implementation for each delegate
concrete instance and so making a new generic method for each different
type wouldn't make sense.
In other words, all possibilities are valid designs. But they
definitely don't do the same thing, so which one is best for your
purposes really depends on what you are trying to do.
Pete