Skip to main content
2 of 3
Edited to use the "return default fallback" as identified in question comment.
ANeves
  • 3k
  • 18
  • 29

"Fast" is not too relevant here, since it's such a simple method.
And the canned response also applies: if you want to improve the speed, first do some benchmarking to know where the bottlenecks really are.

But here my proposal of a better way:

private const string DefaultEmployeeName = "JDoe";
/// <param name="userName">Format expected: "Domain\Name"</param>
private string ParseEmployeeName(string userName) {
    if (userName == null) {
        return DefaultEmployeeName;
    }
    // Username coming is "RandomDomain\RandomLengthUsername.whatever"
    // Let's split by '\', returning maximum 2 substrings.
    // The second (n) will contain everything from the first (n-1) separator onwards.
    string[] parts = userName.Split(new char[] { '\\' }, 2);
    if (parts.Length < 2) {
        return DefaultEmployeeName;
    }
    // Let's remove whitespace, just in case.
    string name = parts[1].Trim();
    if (string.IsNullOrEmpty(name)) {
        return DefaultEmployeeName;
    }
    return name; // "RandomLengthUsername.whatever"
}

The comment with /// on top is a "documentation comments".
They will enrich the Intellisense view of the method, providing extra information.

ANeves
  • 3k
  • 18
  • 29