HowTos for Decorators

czrpb

New member
Joined
Aug 25, 2022
Messages
1
Programming Experience
10+
hi!

i am looking to do Decorators (similarly and simply like python) and so any and all links to blog posts, documentations, etc will be greatly welcomed!

here is a bit of python id like to replicate in c#:

Python:
def before(f):
  def new_f(*args, **kwargs):
    print("before the function")
    return f(*args, **kwargs)
  return new_f

def after(f):
  def new_f(*args, **kwargs):
    result = f(*args, **kwargs)
    print("after the function")
    return result
  return new_f

@before
def add_one(n):
  print(f"adding 1 to {n}")
  return n+1

@after
def sub_one(n):
  print(f"subtracting 1 from {n}")
  return n-1


print(add_one(10))

print()

print(sub_one(9))

% python decorators.py
before the function
adding 1 to 10
11

subtracting 1 from 9
after the function
8

thx!!
 
Last edited by a moderator:
C# doesn't have an equivalent pie syntax for decorators like Python. You'll have to do things using Action, Func, or delegates and keep track of references like you would in Python without using the pie syntax.

As a quick aside, if you say "decorator" to a C# or Java programmer, what comes to their mind will be the Decorator Design Pattern:
 
Back
Top Bottom