How do I create a generic method with a generic in the where clause? (Man that's clear as mud!)

StackOverflow https://stackoverflow.com/questions/4556576

  •  14-10-2019
  •  | 
  •  

Question

Is there a way of doing this:

protected void SubscribeToEvent<TEvent, TPayload>(Action<TPayload> a_action)
    where TEvent : CompositePresentationEvent<TPayload>
{
    TEvent newEvent = _eventAggregator.GetEvent<TEvent>();
    SubscriptionToken eventToken = newEvent.Subscribe(a_action);

    _lstEventSubscriptions.Add(new KeyValuePair<EventBase, SubscriptionToken>(newEvent, eventToken));
}

without requiring the user to specify a TPayload parameter?

Was it helpful?

Solution

No, there isn't. Not in C# 4. You can't do that with a single method.

TEvent cannot be inferred from the arguments passed to the method, and since partial inference is not available for generic type arguments, you'll have to manually specify the type argument at call site.

OTHER TIPS

Believe it or not, VB.NET has something very much like this for extension methods.

Say I have the following extension method:

<Extension()>
Function Append(Of TInferred, T)(ByVal source As IEnumerable(Of TInferred)) As Object()
    Dim items As List(Of Object) = source.Cast(Of Object).ToList()

    Dim value As T = Nothing ' equivalent to default(T) '
    items.Add(value)

    Return items.ToArray()
End Function

Then I could actually call this method passing a single type parameter, for T only, with TInferred being inferred:

Dim strings = New String() {"A", "B", "C"}

' Notice I am passing only one type argument. '
Dim objects = strings.Append(Of Integer)()

For Each obj As Object In objects
    Console.WriteLine(obj)
Next

Output:

A
B
C
0

Sadly, as Mehrdad has indicated, this is not possible in C#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top