Sometimes, a developer just needs to take the long way around. Sure, a line of code like DateTime StartTime = DateTime.Now looks simple and readable, but what happens if you want the StartTime variable to be not exactly now?

Craig’s co-worker figured out a better solution:


public string SomeFunc() {
  DateTime StartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 
    DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
  //… do stuff
}

So much better.

Now, though, we have a string that’s guaranteed to exist and be at least 6 characters long. We need to get the last six characters of that string. We could use a substring function, but that wouldn’t give us an opportunity to use our knowledge of LINQ functions. Kelly found this superior solution:

public string LastSixDigits
{
 get
 {
   if (string.IsNullOrWhiteSpace(this.Number) || this.Number.Length < 6)
     return string.Empty;
   return this.Number.Reverse().Take(6).Reverse().Aggregate(string.Empty, (s, c) => s += c);
 }
}

Finally, one of Jonathan’s peers needed to store a pair of strings as a single object. They could have used one of the many built-in types for that task, like a Tuple or KeyValuePair, but would that have provided a suite of overridden operators?

  public struct StringString
   {
       public string Key;
       public string Value;

       public static bool operator ==(StringString dataItem1, StringString dataItem2)
       {
           return (dataItem1.Key == dataItem2.Key && dataItem1.Value == dataItem2.Value);
       }

       public static bool operator !=(StringString dataItem1, StringString dataItem2)
       {
           return (dataItem1.Key != dataItem2.Key || dataItem1.Value != dataItem2.Value);
       }

       public override bool Equals(object obj)
       {
           if (!(obj is StringString))
           {
               return false;
           }

           return (this == (StringString)obj);
       }

       public override int GetHashCode()
       {
           return (Key.GetHashCode() + Value.GetHashCode());
       }
   }
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!