Search code examples
c#keyedcollection

Want some help understanding this method


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


Solution

  • 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