Repository navigation
Description
Background and motivation
Motivating csharplang discussions: dotnet/csharplang#8343 dotnet/csharplang#7785
Today, delegates are nominal types, and delegates with matching signatures are not interchangeable. Func<T, bool> != Predicate<T>. It would be ideal to be able to declare delegates by their signature rather than by their nominal type, similar to how function pointers can be declared. delegate<T, bool> (or whatever syntax C# decides to go with).
Moreover, at a fundamental level, delegates need not be more than an object reference + a function pointer. The existing class-based delegates have a lot more baggage, making them less efficient than they theoretically could be.
Details
The runtime adds new structural delegate types, along with new IL metadata to use them.
A delegate declared in assembly A delegate<T, bool> and a delegate declared in assembly B delegate<T, bool> are the exact same type, and therefore are identity convertible. delegate<ref T, void> can be used also.
System.Delegate type already exists, so a new base type can be added.
namespace System;
public abstract class StructuralDelegate : ValueType
{
}Yes, structural delegates are struct-based instead of class-based. It essentially looks like this:
public struct delegate<T, TResult> : IEquatable<delegate<T, TResult>>
{
private object _obj;
private void* _mPtr;
// ...
}These new structural delegates do not support Begin/EndInvoke or multi-cast like existing delegates.
To avoid possible tearing of the struct due to thread races, each read/write of a structural delegate will be made atomic by the runtime (this may be blocked by #105054 or #31911). If a struct contains structural delegate fields (or nested struct with structural delegate fields), copying that struct requires each structural delegate field to be copied atomically (the entire struct copy need not be atomic). As an optimization, the atomic r/w could be relaxed if the target is on the stack instead of the heap.
Additionally, to ensure that these structural delegate types are "safe" managed types, the GC should be taught to specially treat the function pointer as an ALC reference.
These types should also be specially treated similar to Nullable<T>, such that comparing to null becomes the same as comparing the pointer to zero, and boxing a default value results in a null object. With that in mind, Nullable<delegate<>> may also need to be treated specially.
There could also be additional APIs to convert to/from existing delegates, or bypassing the atomic r/w with Unsafe, and other APIs that exist for current delegates, but those can be left to future proposals if this ever goes anywhere.
Feature Usage
public class MyEvent<T>
{
// Not thread-safe, but this should get the point across.
private HashSet<delegate<T, void>> _callbacks = new();
public void AddListener(delegate<T, void> callback)
=> _callbacks.Add(callback);
public void RemoveListener(delegate<T, void> callback)
=> _callbacks.Remove(callback);
public void Raise(T arg)
{
foreach (var callback in _callbacks.ToArray())
{
callback(arg);
}
}
}// Very common pattern
public class MyComponent : IDisposable
{
private readonly MyEvent<int> _event;
public MyComponent(MyEvent<int> e)
{
_event = e;
// Existing delegate allocates here, new structural delegate does not allocate.
e.AddListener(OnEvent);
}
public void Dispose()
{
// Existing delegate allocates here, new structural delegate does not allocate.
_event.RemoveListener(OnEvent);
}
private void OnEvent(int arg)
{
// ...
}
}Alternative Designs
-
Structural delegates are class-based like existing delegates. This avoids the issue with atomic r/w and ALC reference, but also adds allocations and other overhead.
-
Disregard atomic r/w and allow developers to shoot themselves in the foot (greatly simplifies implementation, but makes them unsafe).
Risks
Enforcing atomic r/w could impact performance of shared generics in AOT runtimes.
Activity
huoyaoyuan commentedon Aug 18, 2024
This would be a massive feature request, rather than API request.
I'm positive to this, but I'd hope we can include more if we are making changes to this.
teo-tsirpanis commentedon Aug 18, 2024
I am not sure that the need for this feature justifies the required work to design and implement it. The request already mentions metadata changes and three quite major special cases for the JIT, the GC and the type system. With function pointers being always available for the performance-minded people that don't care about capturing objects or unloadability, I cannot see what niche struct delegates would fill.
Some of the ideas described here can be extracted into individual feature suggestions:
Func<T,bool>andPredicate<T>) as the same types in the eyes of the compiler and the runtime.()operator like C++ has, or supporting directly invoking values of types with anInvokemethod.Begin/EndInvokemethods.I remember reading that multicast delegates are pay-to-play, i.e. if you don't use them they won't affect performance.
neon-sunset commentedon Aug 18, 2024
I think the way for successful structural delegates is a generalized shape provided by an interface abstraction (IDelegate, IAction, IFunc, etc.) that users can provide struct implementations for and constrain generic arguments on. Then Roslyn could target that by emitting anonymous struct-based delegate implementations for methods eligible for those. To better enable scenarios that are currently replicated by hand e.g in TensorPrimitives.
Notably, function pointers are not a performance optimization in such case as they do not enable monorphization and subsequent inlining of delegate calls. Nor they enable struct or ref struct closures.
teo-tsirpanis commentedon Aug 18, 2024
I understand that static genericity on functions instead of data types is sometimes needed, but I am not sure if it's a good idea to make this easily accessible by elevating it to a first-class language feature. I am concerned by its downsides (increase in generated machine code size and fragility when used across logical modules) and its potential for abuse which I have seen happening in C++.
How common do you believe are the cases where this would be beneficial? I don't personally believe that merely low-level code like
TensorPrimitiveswould meet the bar.[-][API Proposal]: Structural Delegates[/-][+][Feature Proposal]: Structural Delegates[/+]timcassell commentedon Aug 19, 2024
Very true. I just worked from the issue template.
Can you elaborate?
timcassell commentedon Aug 19, 2024
Yeah, I kinda figured that would be the reaction to this proposal.
It's a similar niche to ref structs, possibly wider reaching, since just about everyone uses delegates, while not everyone uses ref structs.
Considering the amount of effort put into improving performance and usability of safe managed code in .Net recently, this proposal is along the same trajectory, and shouldn't be dismissed just because it's a large amount of work, IMO.
That looks like an issue that has been open for 9 years with no action. #4331
I don't know all the details about it, but I wouldn't be surprised if there are complications and possibly breaking changes by changing the type compatibility of existing delegates.
This proposal is a fresh start from scratch, new types, no worries about breaking anything.
I'm not sure where that came from. This proposal has absolutely nothing to do with an invoke operator.
Those were mentioned, not because it may or may not be possible to exclude them on existing delegates, but just to highlight that the new types absolutely will not support them.
timcassell commentedon Aug 19, 2024
That looks like the functional interfaces proposal. dotnet/csharplang#3452
That is similar to this proposal, but serves a different purpose. Namely, it can achieve zero allocation by using variable-sized structs, while this is a fixed-size type.
33 remaining items
TahirAhmadov commentedon Nov 12, 2025
Even if so, how does that negatively impact that usage scenario? If you get the same syntax and behavior, what does it matter how the underlying stuff is implemented?
timcassell commentedon Nov 12, 2025
What same syntax and behavior? I can't use
Action<ref T, out U>.TahirAhmadov commentedon Nov 12, 2025
You can't today, but it can be made possible with new syntax, no? Fundamentally,
refis a type, and direction can be made an attribute.I do think you should reassess your aversion to nominal delegate types. I find it hard to believe that copying and pasting stuff like
Action<ref int, string, out bool, in Guid>is preferable to a simple identifier.timcassell commentedon Nov 12, 2025
I prefer to not have extra boilerplate of delegate creation, and I like to see at the usage place what the signature of the delegate is without having to jump to the delegate declaration. It's also immediately clear to me when a parameter is a delegate as opposed to some other type. And as a library author, I'd rather not pollute the amount of delegate types in the app.
TahirAhmadov commentedon Nov 12, 2025
The moment the same delegate type is referred to more than once, the cost shifts: you get the boilerplate of delegate usage.
And I think when it comes to simple "pass a delegate to one method and it gets used in that method" scenario, more often than not it's a simple delegate like
Func<,>or similar, and those do exist (for better or for worse). It's the complex ones withref/outetc. stuff that I don't understand the need for "saving boilerplate of creation".Even if you have a method which takes a delegate and it's called in that method (meaning, it's not passed/stored anywhere), it's more difficult to read together with other parameters (if you have them): literally yesterday I was reading my own code from a year ago where I used an anonymous delegate, and it all got blurred in my eyes, which identifier is part of the delegate generics, which one is a parameter type, etc.
PS. Needless to say, I immediately got rid of all that stuff and declare
privatenested delegate and record struct types (for tuples); took me all of 2 minutes, and then in 10 seconds, I made sense of what my OWN code did; I was struggling to do so with the anonymous stuff.That same logic can be extended to most DTOs - you don't want to jump to
Personclass to see it has a first name and a last name, why not just pass everything by tuple? If we're doing away with nominal delegate types altogether, that means you want to see all 8, 18, or however parameters it has - how is this different from a data object of some sort with N properties?Meh, it's easy enough to append the word Delegate to the type name.
What's the problem with having more types in your library?
Bottom line is, I don't mind you writing code with more "anonymous" types, like these "structural" delegates, but you are advocating for taking away the ability of others to create nominal types of delegates. I don't think I want to convince you to change your ways, but I do hope you grant me and others that we want to do it our way.
timcassell commentedon Nov 12, 2025
When that happens, I just separate the parameters to new lines. It's very easy to read.
Exactly, and I love tuples for that reason also. I use tuples all the time for e.g. passing captured data to a delegate to avoid closure allocations. Or intermediate transforms in Linq queries.
It's not my library, it's all the libraries and user assembly combining all of their declared delegates with potentially duplicate signatures. If it's structural, it's all runtime and there are no duplicates.
I'm not advocating for removing the ability to do what you like. I just think there are other ways to achieve it besides nominal delegates (like type aliases and roles).
TahirAhmadov commentedon Nov 12, 2025
Which is more work, put new lines, indent everything nicely, etc. Not really "less work".
These are valid use cases - come to think of it, the only times I use them is to replace allocated anonymous types, and prevent closure allocations. I do think we could have better solutions for those; I created a C# discussion for an allocation-free closure for immediately called methods. The entire LINQ is overdue for optimization itself with struct enumerables, etc.
However, I was referring to method return types, fields, etc. - in none of those scenarios, do tuples make the code easier to read and maintain. I experienced it myself - I quickly put together a tuple, come back a few months later, and I'm trying to remember what I did, Nominal types are self-documenting. It's not about writing code fast, rather about writing code which can be maintained and improved over time.
If these delegate types are internal, then nobody sees them outside, so they don't pollute. And if they're public, they better have a name, plus documentation for what it's supposed to do. And we do NOT want unrelated delegates from various assemblies to be assignable to each other just because the signatures match. It's like saying, you have a
Studentwith first name and last name, andTeacherwith same fields, so variable of type "student" can implicitly get a value of type "teacher" (because there are no types, per se) and developer doesn't get any warning whatsoever. It's a pit of failure.None of those give me the ability to have a type safe reference to a method.
TahirAhmadov commentedon Nov 12, 2025
PS. I wish we could get a combination of anonymous types and tuples; meaning, a syntax which would create a strongly-typed inline-defined record struct, for the LINQ stuff. It's unlikely to happen at this point, but that's what I would do in a clean-slate C#.
TahirAhmadov commentedon Nov 12, 2025
PPS. Even worse, you have a "student" with first and last names, and a "vehicle" with make and model. One wrong variable assignment, and you have Chevy Malibu trying to learn ancient Greek literature. 🤣 Sorry, but no. Just a bad idea, IMO.
timcassell commentedon Nov 12, 2025
The roles feature absolutely would give you delegate type safety (a shame it got put on the back-burner during extension everything). One other thing that I think would help with the self-documenting problem is if C# supported named type arguments (I remember seeing a proposal for it, but I don't have the link on hand).
TahirAhmadov commentedon Nov 12, 2025
So we have 2 options - expensive runtime changes to support variadic type arguments, and expensive runtime changes to support roles the way their proponents would like them to work, in order to make this feature structural first; or neither one of those costs in terms runtime of work, with nominal first approach, and structural being just syntax sugar on top. The function pointer problem needs to be solved in both cases. So why choose the vastly more expensive option?
PS. The syntax for "structural" delegate syntax can already be added to existing delegates and some work has already been done in that direction (to my dismay). That's why there's no reason to necessarily couple the two concepts for value type delegates; and this is ignoring the whole debate over that structural approach even being a good pattern to follow. Basically, we have a pattern which is at best controversial, which can be added as a language feature, but you insist that it's baked in at great cost purely out of your aversion to nominal types. I fail to see the rationale behind this stance.
TahirAhmadov commentedon Nov 12, 2025
Regarding
MethodInfo, I understandInvokecalls cannot be generated in IL for ref types, but can the IL contain something to convert the underlying method reference to a pointer and call that like you're proposing, with the understanding that JIT will understand this "dirty" sequence and optimize it to a simple call in machine code?PS. I keep thinking in this direction because I have a suspicion that even this weird workaround is easier to accomplish than pointer lifetime tracking (but I may be wrong on this. )
timcassell commentedon Nov 12, 2025
Delegates cannot be made structural on top of nominal types purely through language changes. It will require runtime changes either way.
Delegates are a fundamental type. The fact that they are nominal has always seemed strange to me. Function pointers are structural, this is pretty much aligning them. There's not much difference between a function pointer and a delegate except 1 carries state (and all the other historical baggage that's not part of this proposal).
Either way it's a lot of work. If the end result in syntax is the same, then really the only tradeoff is whether delegates declared in separate assemblies with matching signatures have the same underlying runtime type.
timcassell commentedon Nov 12, 2025
If struct delegates go a similar route as class delegates, the runtime can implement it as it sees fit, using a method info or modifying the GC. I could imagine it using method info for the initial implementation, then later use direct function pointer for more performance.
TahirAhmadov commentedon Nov 12, 2025
They won't be "structural" really, but surely we can devise syntax which uses new BCL types to achieve a similar effect?
The same can be said about any pointer, "a class reference is just a pointer which is tracked by GC", etc. But there is a difference, and a huge difference - safety. Just like .NET mandates that references point at objects, not just at memory, delegates are a type safe way to invoke a method, not just a pointer to
callwith machine code. I totally agree with you that the heap storage of them and multicast stuff is unnecessary overhead, but it doesn't suddenly make struct delegates and function pointers identical.I disagree. I think the whole "we make a magical struct which can have unlimited number of type arguments" is a much bigger change, than creating another copy-pasta of 16 types in BCL to be the basis of "syntax" "structural" delegates on the language level.