Is there a way to have extension method on the method? Example for this would be method that takes some user object as parameter and you need to do security check if that user can use that method at the very beginning of the method. Can the method have extension method like "check can this user use me" and return bool.
Thanks.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods.
You can use Aspect Oriented Programming (AOP) to implement cross-cutting security checks in your code.
In .NET you have a choice of several AOP frameworks, for example:
In particular the PostSharp documentation has some nice examples on how to implement security using AOP.
You can't add extension method for a method with C#.
But you could use Aspect Oriented Programming (AOP) to do what you want, using PostSharp or Spring.NET for example.
Example of securing methods with PostSharp
public class BusinessDivision : BusinessObject
{
[SecuredOperation("Manager")]
public void EnlistEmployee(Employee employee)
{
// Details omitted.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With