Issues with Delegates

Issues with Delegates

Delegates are similar in principle to C/C++ function pointers and are used by the .NET Framework to support events. If your code accepts delegates, you have no idea a priori what the delegate code is, who created it, or what the writer's intentions are. All you know is the delegate is to be called when your code generates an event. You also do not know what code is registering the delegate. For example, your component, AppA, fires events; AppB registers a delegate with you by calling AddHandler. The delegate could be potentially any code, such as code that suspends or exits the process by using System.Environment.Exit. So, when AppA fires the event, AppA stops running, or worse.

Here's a mitigating factor delegates are strongly-typed, so if your code allows a delegate only with a function signature like this

public delegate string Function(int count, string name, DateTime dt);

the code that registers the delegate will fail when it attempts to register System.Environment.Exit because the method signatures are different.

Finally, you can limit what the delegate code can do by using PermitOnly or Deny for permissions you require or deny. For example, if you want a delegate to read only a specific environment variable and nothing more, you can use this code snippet prior to firing the event:

new EnvironmentPermission( EnvironmentPermissionAccess.Read,"USERNAME").PermitOnly();

Remember that PermitOnly applies to the delegate code (that is, the code called when your event fires), not to the code that registered the delegate with you. It's a little confusing at first.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net