diff --git a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj index e2611c0..0774ec3 100644 --- a/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj +++ b/ICD.Common.Utils/ICD.Common.Utils_SimplSharp.csproj @@ -87,6 +87,7 @@ + diff --git a/ICD.Common.Utils/ReprBuilder.cs b/ICD.Common.Utils/ReprBuilder.cs new file mode 100644 index 0000000..c03e83f --- /dev/null +++ b/ICD.Common.Utils/ReprBuilder.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using System.Text; + +namespace ICD.Common.Utils +{ + /// + /// Simple class for building a string representation of an object. + /// + public sealed class ReprBuilder + { + private readonly object m_Instance; + + private readonly List m_PropertyOrder; + private readonly Dictionary m_PropertyValues; + + /// + /// Constructor. + /// + /// + public ReprBuilder(object instance) + { + m_Instance = instance; + + m_PropertyOrder = new List(); + m_PropertyValues = new Dictionary(); + } + + /// + /// Adds the property with the given name and value to the + /// + /// + /// + public void AppendProperty(string name, object value) + { + m_PropertyOrder.Remove(name); + m_PropertyOrder.Add(name); + + m_PropertyValues[name] = value; + } + + /// + /// Returns the result of the builder. + /// + /// + public override string ToString() + { + if (m_Instance == null) + return GetValueStringRepresentation(m_Instance); + + StringBuilder builder = new StringBuilder(); + + builder.Append(m_Instance.GetType().Name); + builder.Append('('); + + for (int index = 0; index < m_PropertyOrder.Count; index++) + { + string property = m_PropertyOrder[index]; + builder.Append(property); + builder.Append('='); + + object value = m_PropertyValues[property]; + string valueString = GetValueStringRepresentation(value); + builder.Append(valueString); + + if (index < m_PropertyOrder.Count - 1) + builder.Append(", "); + } + + builder.Append(')'); + + return builder.ToString(); + } + + private static string GetValueStringRepresentation(object value) + { + if (value == null || value is string) + return StringUtils.ToRepresentation(value as string); + + return value.ToString(); + } + } +}