Handling Specific Types Unknown at Compile C# with Example
Time The following output equivalent results: class IfElseExample { public string DebugToString(object a) { if (a is StringBuilder) { return DebugToStringInternal(a as StringBuilder); } else if (a is List) { return DebugToStringInternal(a as List); } else { return a.ToString(); } } private string DebugToStringInternal(object a) { // Fall Back return a.ToString(); } private string DebugToStringInternal(StringBuilder sb) { return $"StringBuilder - Capacity: {sb.Capacity}, MaxCapacity: {sb.MaxCapacity}, Value: {sb.ToString()}"; } private string DebugToStringInternal(List list) { return $"List - Count: {list.Count}, Value: {Environment.NewLine + "\t" + string.Join(Environment.NewLine + "\t", list.ToArray())}"; } } class DynamicExample { public string DebugToString(object a) { return DebugToStringInternal((dynamic)a); } private string DebugToStringInternal(object a) { // Fall Back return a.ToString(); } private string DebugToStringInternal(StringBuilder sb) { return $"StringBuilder - Capacity: {sb.Capacity}, MaxCapacity: {sb.MaxCapacity}, Value: {sb.ToString()}"; } private string DebugToStringInternal(List list) { return $"List - Count: {list.Count}, Value: {Environment.NewLine + "\t" + string.Join(Environment.NewLine + "\t", list.ToArray())}"; } } The advantage to the dynamic, is adding a new Type to handle just requires adding an overload of DebugToStringInternal of the new type. Also eliminates the need to manually cast it to the type as well.