-2
class SetMap : KeyedCollection<Type, object>
{
    public HashSet<T> Use<T>(IEnumerable<T> sourceData)
{
    var set = new HashSet<T>(sourceData);
    if (Contains(typeof(T)))
    {
        Remove(typeof(T));
    }
    Add(set);
    return set;
}

public HashSet<T> Get <T>()
{
    return (HashSet<T>) this[typeof(T)];
}

protected override Type GetKeyForItem(object item)
{
    return item.GetType().GetGenericArguments().Single();
}
}

would anyone clarify this for me pls. return (HashSet) this[typeof(T)]; with example if possible. thank you

Abbas
  • 13
  • 3

2 Answers2

0

It is using generics. A modern programming concept that makes it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

In your example it is defining a hashset that can hold any type.

Read the MSDN documentation in the links I've provided and if you have a more specific questions post them here.

Guy Lowe
  • 2,115
  • 1
  • 27
  • 37
  • to be specific i don't understand this[typeof(T)]. whats happening here ? – Abbas Nov 10 '15 at 05:40
  • it is checking the type to see if there is an object of that type (typeof) in the hashset and then if it is it removes it. – Guy Lowe Nov 10 '15 at 05:56
0
return (HashSet) this[typeof(T)];

Let me split the statement into parts.

(1) this[...] means using the indexer of this. And this basically means "this object".

(2) The indexer accepts a Type. And in this call to the indexer, the argument is typeof(T).

(3) typeof gets a Type object that corresponds to the type in the (). In this case, the generic type parameter T. And the indexer returns an object.

The parameter (Type) and return type (object) of the indexer can be inferred from the base type of the class: KeyedCollection<Type, object>. I think you can understand this.

(4) The value returned by the indexer gets casted into a HashSet<T>. Again, T is the generic type argument.

(5) The value gets returned to the caller by the return statement.

For more information:

  1. Indexers: https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

  2. Generics: https://msdn.microsoft.com/en-us/library/512aeb7t.aspx

  3. Casting: https://msdn.microsoft.com/en-us/library/ms173105.aspx\

  4. KeyedCollection: https://msdn.microsoft.com/en-us/library/ms132438(v=vs.110).aspx

  5. typeof: https://msdn.microsoft.com/en-us/library/58918ffs.aspx

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • thanks for the helpful answer, one more question how do we know that KeyedCollection implements the indexer so that we used "this"? or all collections implement it? – Abbas Nov 10 '15 at 06:11
  • @Abbas I think so. All `ICollection` implements an indexer that accepts a parameter of type `T` – Sweeper Nov 10 '15 at 07:38