Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"To" vs "As" vs "Get" Method Prefixes

Tags:

c#

.net

vb.net

Does anyone know of any naming convention rules/guidelines that dictate when to use a "To" prefix (myVariable.ToList()), an "As" prefix (myVariable.AsEnumerable()), or a "Get" prefix (myVariable.GetHashCode())?

like image 773
Kerby Avatar asked Dec 13 '12 20:12

Kerby


3 Answers

I assume there's no convention, so just use what fits best to what you're doing.

  • "To" creates something new/ converts it
  • "As" is just a "different view" on the same f.e. by using iterators
  • "Get" is a getter for everything else
like image 169
Tim Schmelter Avatar answered Nov 03 '22 16:11

Tim Schmelter


My understanding/conventions:

"To" performs a conversion; A new object is created in memory, based on the data inherent in your source.

"As" performs a cast; The same reference passed in is returned behind the "mask" of a different type.

"Get" performs pretty much anything else that takes in a source and whose primary product is a transformed result. Gets can perform a calculation, return a child, retrieve data from a store, instantiate objects from a default state, etc. Not all such methods have to be named "Get", but most methods intended to calculate, instantiate, project, or otherwise transform, and then return the product as their primary purpose are "getters".

like image 3
KeithS Avatar answered Nov 03 '22 16:11

KeithS


  1. When myObj is not related to List, prefix "To" to convert.
  2. When myObj is a subclass of Enumerable, prefix "As" to give it as Enumerable
  3. When myObj is not related to List, but it composes / can compose List use "Get" prefix
like image 1
humblelistener Avatar answered Nov 03 '22 14:11

humblelistener