Reputation: 43
See the example below...
public class Test
{
public delegate void Logger(string s);
public void Process(Logger logger)
{
if (logger!= null)
{
logger("Process Started");
}
if (logger != null)
{
logger("Process End");
}
}
}
class Program
{
public static void LogMe(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
Test obj = new Test();
Test.Logger del = new Test.Logger(LogMe);
obj.Process(del);
}
}
Here Delegate Logger is written in class Test ... when I create the object of Class Test i.e. obj... the delegate Logger is not listed there and when tried using class name I'm able to get the Logger.
I know the delegate concepts but I just want to understand why delegate is not listed in obj list.
Upvotes: 2
Views: 442
Reputation: 606
If you were to mention the delegate outside of the test class at the name space level:
namespace StackOverflow{
public delegate void Logger(string s);
public class Test
{
}
}
you would be able to access the Logger type without the prefix of the test class. Partly because we have often seen Delegate as a nested type we don't realize its a type and can stand its own in the namespace.
Upvotes: 0
Reputation: 70671
when I create the object of Class Test i.e. obj... the delegate Logger is not listed there and when tried using class name I'm able to get the Logger
A type nested within another type is not an instance member. Even though the keyword static
is not applied to the declaration of the nested type, in some sense it's still "static". (Though, it's not a run-time member in the sense that you could call a method or access a field or property, so I'm not sure I would really consider it a "static member" either).
More basically, the delegate type Logger
is not in any way a per-instance member of the class. I.e. each instance cannot have a different Logger
. So it would not make any sense to access the Logger
type through an instance reference.
And for any member of a class that isn't per-instance, you access it by using the type name instead. E.g. Test.Logger
.
If the delegate type is in some way unique to Test
and is closely tied to the public API of Test
, then perhaps the nested type makes sense here. That said, I tend to try to avoid public nested types, using them only when it seems really, strongly the right thing to do, mainly because of this specific issue. I don't like having to quality type names with a containing type name. :)
You do have some alternatives:
Action<string>
would work just as well.using
statement.using Logger = MyNamespace.Test.Logger;
at the top of a source code file where you want to use the type, and then you can use it with just the shorter Logger
. (Replace MyNamespace
with whatever your actual fully-qualified namespace for the type is, of course).Upvotes: 3