Ref Returns
04/25/2019
C# has recently introduced some new features (version 7.0) one of which it is ref returns. I will use this feature in this post to further improve the performance of the Parser created in my previous post.
To refresh the Parser
class looked as follows:
public class Parser { public T Parse<T>(ReadOnlySpan<char> input, PropertySetter[] setters) where T : struct { T result = default; int separator; int propertySetterIndex = 0; while((separator = input.IndexOf(',')) != -1) { var parsedValue = int.Parse(input.Slice(0, separator)); setters[propertySetterIndex++].SetValue(ref result, parsedValue); input = input.Slice(separator + 1); } return result; } }
To recap it receives an input of comma separated integers that we are parsing into a struct of the user's choice: T
. Extending it to other than integer types and fixing the possible ArgumentOutOfRangeException
is not a concern of this blog post.