In the code below I created a delegate named Mhd
- just like the Action
delegate.
My question: if the two delegates are public, why only Action
delegate is visible from another class and not Mhd
?
static void Main(string[] args)
{
new Test().Yaser(); //this can be done
new Test().mhd(); //this can not be done
}
class Test
{
public Action Yaser;
public delegate void Mhd();
}
//and Action definition is public delegate void Action();
any help is appreciated :)
Because
Mhd
is not a member of your class. It's a delegate type that you declared in your class.So you can't treat it like a member method or property but you can use it to declare a variable of that type
For my answer to make sense, it's important to remember the definition of a delegate. According to MSDN:
A delegate is a reference?!?!
If you are familiar with C++, you know that another way of saying reference is pointer. (In fact, C++ developers get similar functionality to C# delegates via function pointers.)
What is the significance of delegates being references? Among the basic constructs provided by the common type system, the .NET Framework has another reference type:
class
. Saying that a delegate is a reference type is just like saying that a delegate is a class. Let's review how we use classes.There are 3 steps you need to follow before you can use an instance of a class:
class Test { public Action Yaser; }
class Test testClassObject;
testClassObject = new Test();
(Typically, we combine instance declaration and instantiation).
We said that delegates are classes. Therefore, delegate use follows the same pattern:
public delegate void Mhd();
public Mhd myMhd;
myDelegateField = new Mhd(SomeMethod);
But wait, what is
SomeMethod
? Truly, it doesn't matter. All that we know is that its signature must match that of Mhd. In other words,void SomeMethod()
Let's inspect and fix your class declaration. A possible implementation is shown below:
declares a field of type
Action
, whereasdeclares the
Mhd
as delegate type.