C# method naming conventions: ToSomething vs. AsSomething

Solution 1:

ToDictionary and ToList are prefixed with To because they don't necessarily preserve the structural identity of the original collection or its properties.

  • Transforming a List<T> into a Dictionary<K, V> creates a collection with a whole new structure.
  • Transforming a HashSet<T> into a List<T> removes the uniqueness property of sets.

Methods prefixed with As don't do any of these things - they simply provide an alternative view of the original collection. They enrich it.

Solution 2:

In Linq, the ToXXX methods all execute the query and create a new object from the results, while the AsXXX methods produce a new query which is different in some way. It may be the same object but accessed through a different interface (AsEnumerable() does this) or it may be a new object that alters the functionality (the other methods do this, though some check to see if they can just return the given object, e.g. AsQueryable() will return source if it implements IQueryable<T> already, or create a new EnumerableQuery<TElement> otherwise).