C# method naming conventions: ToSomething vs. AsSomething
C#Naming ConventionsC# Problem Overview
As I was writing some extension methods for my business logic objects, I came to the question of renaming the conversion methods. someObject.ToAnotherObject()
would go fine with the widely used object.ToString()
.
However LINQ, for example, mixes up both variants and I can't find a difference between them. ToDictionary()
, ToList()
, AsParallel()
, AsQueryable()
, ...
What are the differences between these two naming conventions and what should I know to decide whether to use for my own classes?
C# Solutions
Solution 1 - C#
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 aDictionary<K, V>
creates a collection with a whole new structure. - Transforming a
HashSet<T>
into aList<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 - C#
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).