user400055
user400055

Reputation:

C# Generics with 'Wildcards'

I'm looking for a way to get wildcards to work in .NET generics.

My code is as follows:

private class Rule<TSource, TSelected> where TSource : class where TSelected : class
{
    // stuff in here
}

I want to be able to create a List<> of Rules where the TSource will be the same but the TSelected may be different.

Upvotes: 1

Views: 147

Answers (3)

beruic
beruic

Reputation: 5876

If the TSelected classes has the same super-class, you can just make a list of Rule<TSource, TSelectedSuperClass>. I believe you can use typeof (http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx) to get the exact subclass after reading the TSelected object again.

Alternatively you can make a container class to contain both and also store the exact types.

An interface could do it instead of a super class. If the Selected share implementation however, I prefer an abstract class.

Upvotes: 0

Jon
Jon

Reputation: 437414

You need to make a contravariant generic interface IRule<TSource, in TSelected> and make a list of that, where in addition TSelected is going to be constrained to some meaningful class. Constraining to any reference type as in your existing code will compile, but you won't be able to do anything meaningful with anything that has to do with TSelected.

At this time there is no other way to use variant generics (unless of course you go into reflection mode with List<dynamic> or something equivalent), so if this solution does not work for you you will need to redesign.

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38825

If I read your question right, I think you'd have to do this:

public interface ISelected
{
    // ISelected interface
}

// A TSelected implementation
public class Implementation1: ISelected { }
// Another
public class Implementation2 : ISelected { }

// our Rule
private class Rule<TSource, TSelected> where TSource : class where TSelected ISelected
{
}

Upvotes: 0

Related Questions