Themelis
Themelis

Reputation: 4245

How to reference a struct's type parameters in a generic C# class?

I would like to create my own implementation of INotifyCollectionChanged but I want the observable collection to be a dictionary. Something like:

MyObservableDictionary<KeyValuePair<TKey, TValue>>

After reading this article on MSDN about generics it seems that you can define that as

public class MyObservableDictionary<T> : INotifyCollectionChanged where T : struct
{
  public event NotifyCollectionChangedEventHandler CollectionChanged;
}

but this

  1. does not enforces that the struct should be of type KeyValuePair and
  2. I don't know how to reference TKey and TValue in the class.

Is there any solution to this?

Upvotes: 0

Views: 301

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Well, you have 2 generic parameters, let them be TKey and TValue:

public class MyObservableDictionary<TKey, TValue> 

Your class implements two interfaces:

  1. "I want the ... collection to be a dictionary" - IDictionary<TKey, TValue>
  2. "I would like to create my own implementation of INotifyCollectionChanged"

Add them:

public class MyObservableDictionary<TKey, TValue> 
  : IDictionary<TKey, TValue>, 
    INotifyCollectionChanged 

Finally, if I've understood you right, you want to restrict both TKey and TValue to be struct only; you can do it with a help of where:

 public class MyObservableDictionary<TKey, TValue> 
  : IDictionary<TKey, TValue>, 
    INotifyCollectionChanged 
  where TKey : struct
  where TValue : struct {
  //TODO: implementation here
}

Upvotes: 2

Arthur Heidt
Arthur Heidt

Reputation: 131

Are you looking for

MyObservableDictionairy<TKey, TValue> : INotifyCollectionChanged where TValue : struct

You can then wrap the key/values into key/value pairs as they are added, or simply have an add method signature like this:

public void Add(KeyValuePair<TKey, TValue> value)

Upvotes: 0

Related Questions