question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Proposal: Support System.Delegate as a generic constraint

See original GitHub issue

Problem

In C# it is currently not legal to specify that a generic type parameter be constrained to System.Delegate.

// CS0702: Constraint cannot be special class 'System.Delegate'
public TDelegate Combine(TDelegate first, params TDelegate[] others) where TDelegate : System.Delegate {
   ...
}

This is a limitation imposed only by the C# compiler. The .NET runtime fully supports generic type constraints of System.Delegate and the C# compiler does support consuming said constraints from assemblies that have been compiled from languages without that limitation:

extension method TDelegate.Combine<TDelegate>(params others: array of TDelegate): TDelegate; where TDelegate is System.Delegate
EventHandler handler1 = (s, e) => Console.WriteLine("this");
EventHandler handler2 = (s, e) => Console.WriteLine("that");
EventHandler combined = handler1.Combine(handler2);  // calling Oxygene extension method

Proposal:

Remove the artificial limitation and allow a generic type constraint to be of type System.Delegate. Since this syntax is currently illegal in C# doing so would not impact any existing code.

Note that I am not suggesting to support the keyword delegate. My opinion is that the keyword be left unsupported for potential future constraint work that would allow specifying a required signature for the delegate which would expose the ability to invoke the delegate. The runtime does not currently support such a notion and it would be unenforceable.

Use Cases

Type-safe helper methods to combine delegates:

public static TDelegate Combine<TDelegate>(this TDelegate source, TDelegate target)
    where TDelegate : System.Delegate {

    return (TDelegate)Delegate.Combine(source, target);
}

Helper methods to subscribe/unsubscribe event fields:

public static void Subscribe<TDelegate>(ref TDelegate field, TDelegate target)
    where TDelegate : System.Delegate {

    // this is the logic emitted by the C# compiler when you define an event with the default adder/remover methods
    TDelegate previous = null;
    TDelegate current = field;
    do {
        previous = current;
        TDelegate proposed = (TDelegate)Delegate.Combine(previous, target);
        current = Interlocked.Exchange<TDelegate>(ref field, proposed, previous);
    } while (previous != current);
}

...

public EventHandler MyEvent {
    add {
        // custom logic here
        // explicitly implementing an event leaves the developer on their own for handling the
        // subscription and using += directly against the event field is inherently not thread-safe
        EventHelper.Subscribe<EventHandler>(ref MyEvent, value); // thread-safe subscription
    }
    remove {
        EventHelper.Unsubscribe<EventHandler>(ref MyEvent, value); // thread-safe unsubscription
    }
}

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Reactions:9
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
alrzcommented, Feb 9, 2016

Delegate is a special class that one could not derive from so to me it doesn’t look right to use it as a constraint like that, I’d prefer delegate instead,

public static void F<T>(...) where T : delegate { ... }
0reactions
gaftercommented, Mar 27, 2017

We are now taking language feature discussion in other repositories:

Features that are under active design or development, or which are “championed” by someone on the language design team, have already been moved either as issues or as checked-in design documents. For example, the proposal in this repo “Proposal: Partial interface implementation a.k.a. Traits” (issue 16139 and a few other issues that request the same thing) are now tracked by the language team at issue 52 in https://github.com/dotnet/csharplang/issues, and there is a draft spec at https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md and further discussion at issue 288 in https://github.com/dotnet/csharplang/issues. Prototyping of the compiler portion of language features is still tracked here; see, for example, https://github.com/dotnet/roslyn/tree/features/DefaultInterfaceImplementation and issue 17952.

In order to facilitate that transition, we have started closing language design discussions from the roslyn repo with a note briefly explaining why. When we are aware of an existing discussion for the feature already in the new repo, we are adding a link to that. But we’re not adding new issues to the new repos for existing discussions in this repo that the language design team does not currently envision taking on. Our intent is to eventually close the language design issues in the Roslyn repo and encourage discussion in one of the new repos instead.

Our intent is not to shut down discussion on language design - you can still continue discussion on the closed issues if you want - but rather we would like to encourage people to move discussion to where we are more likely to be paying attention (the new repo), or to abandon discussions that are no longer of interest to you.

If you happen to notice that one of the closed issues has a relevant issue in the new repo, and we have not added a link to the new issue, we would appreciate you providing a link from the old to the new discussion. That way people who are still interested in the discussion can start paying attention to the new issue.

Also, we’d welcome any ideas you might have on how we could better manage the transition. Comments and discussion about closing and/or moving issues should be directed to https://github.com/dotnet/roslyn/issues/18002. Comments and discussion about this issue can take place here or on an issue in the relevant repo.


This issue is now being tracked at https://github.com/dotnet/csharplang/issues/86 and https://github.com/dotnet/csharplang/issues/103

Read more comments on GitHub >

github_iconTop Results From Across the Web

Proposal: Support System.Delegate as a generic constraint ...
NET runtime fully supports generic type constraints of System.Delegate and the C# compiler does support consuming said constraints from ...
Read more >
C# Generics won't allow Delegate Type Constraints
A number of classes are unavailable as generic contraints - Enum being another. For delegates, the closest you can get is ": class", ......
Read more >
Constraints on type parameters - C# Programming Guide
This constraint applies also to any class, interface, delegate, ... beyond simple assignment or calling any methods not supported by System.
Read more >
Unmanaged, delegate and enum type constraints - C# 7.3 ...
With C# 7.3, three new generic type constraints are introduced (proposal): unmanaged , System.Delegate and System.Enum .
Read more >
Constraining Generics in C#
Delegate or System.MulticastDelegate as a base class constraint. The documentation provide an example and details on using the unmanaged ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found