I understand delegates as a shortcut for defining a class with one method but what is the meaning of bar2 below? It compiles. But I can’t see what an inner class would do here. I know I’m missing something so that’s why I’m asking (this is not homework, I’m at work-work right now).
namespace ns2 { public delegate void bar();}
public class foo
{
private ns2.bar _callback;
public foo(ns2.bar callback) { _callback = callback; }
public void baz() { _callback(); }
public delegate void bar2();
}
Thanks!
It’s just declaring a nested type, that’s all. As it’s public, there’s pretty much no difference between that being declared inside the type and being declared outside.
Other classes will have to refer to it via the name of the containing type (unless they have a
usingdirective specifically for it):Usually when I write a nested type, it’s private – it’s just a helper class for the containing class; an implementation detail. That doesn’t have to be the case, of course, but it should at least be true that the nested type is meaningless unless you’re in some way using the outer class. For example, it could be a builder for the outer class, or an enum used in some parameters for a method call within the outer class.
(By the way, it’s useful when writing sample code like this to follow .NET naming conventions even for meta-syntactic names like
FooandBar. It makes the difference between variables and types clearer, for example.)