First the example as you requested:
void Verbose(string s) { Console.WriteLine(s); }
void Quiet(string s) {}
...
delegate void Print(string s);
...
void DoSomething(Print logger)
{
logger("start...");
...
logger("...done");
}
...
DoSomething(Verbose);
...
DoSomething(Quiet);
...
This is a possible usage.
If ever possible, use interfaces instead of delegates.
public interface ILogging { void Print(string s); }
public class Verbose: ILogging
{
public void Print(sting s) { Console.WriteLine(s); }
}
public class Quiet: ILogging
{
public void Print(string s) {}
}
...
void DoSomething(ILogging logger)
{
logger.Print("start...");
...
logger.Print("...done");
}
...
DoSomething(new Verbose());
...
DoSomething(new Quiet());
...
It's more robust and more universally usable.
But C# interfaces have limits:
- no static methods possible in interfaces
E.g. I
cannot tell something like (this does *not* compile):
public interface ILogging { static void Print(string s); }
public class Verbose: ILogging
{
public static void Print(sting s) { Console.WriteLine(s); }
}
public class Quiet: ILogging
{
public static void Print(string s) {}
}
...
void DoSomething<T>() where T: ILogger
{
T.Print("start...");
...
T.Print("...done");
}
...
DoSomething<Verbose>();
...
DoSomething<Quiet>();
...
Here, you are bound to either having a "seed" object of a class that implements the interfaces (see 2nd example above) or to use delegates (see 1st example).
Cheers
Andi