Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extension method for a method C#

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.

like image 487
eomeroff Avatar asked Oct 08 '10 08:10

eomeroff


People also ask

What is the extension method for a class?

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.

What is extension method with example?

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.

How do extension methods work C#?

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.

Can you add extension methods to an existing static class?

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.


2 Answers

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:

  • Spring.NET
  • PostSharp

In particular the PostSharp documentation has some nice examples on how to implement security using AOP.

like image 61
Martin Liversage Avatar answered Sep 20 '22 04:09

Martin Liversage


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.
        }
    }
    
like image 33
Julien Hoarau Avatar answered Sep 20 '22 04:09

Julien Hoarau