Delegates with states implementation or something similar

33 Views Asked by At

I'm trying to do something similar to what I can do in C++: override the () operator.

I have read that this is not possible in C#, and I can't extend from Action or Function classes.

Is there any way that I can have delegates with attributes or having a callable without adding a function like Invoke to my classes and having the same behavior as in C++?

Regards

1

There are 1 best solutions below

0
On

Is there any way that I can have delegates with attributes

Sure!

[AttributeUsage(AttributeTargets.Delegate )]
public class SimpleAttribute : Attribute { }

[SimpleAttribute]
public delegate void MyDelegate();

If you meant properties or parameters, then no. But you can create a delegate that captures parameters:

public Func<float> SomeFunction(int a, float b){
    return () => a + b;
}

//or
public class MyClass{
    public int A;
    public float B;
    public float Add() => A + B;
}
...
Func<float> addDelegate = new MyClass(){A = 5, B = 4}.Add;

This is very common, and will be compiled down to an object of some compiler generated type.

The main alternative is to create a regular class with a Invoke-method or similar. But you could also use something like (string Name, Action Run) to create a ValueTuple containing a delgate and some other associated data.

Note that C# is fundamentally different from C++. It is in general a safer but less performance oriented language. Many C++ patterns do not translate to C# since the reasons they exist just do not apply.