Converting object to its string representation

When programming in object-oriented, it is good practice to have in each entity class  the method that will display the contents of our object. This method is named ToString ().

Although it already exists by default in modern languages high level as Java or C #, it is not representative. So you have to rewrite it.

object-tostring

An example of the ToString() method in C #, for representing our entire object as a string.

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
            {
                sb.Append(property.Name);
                sb.Append(": ");
                if (property.GetIndexParameters().Length > 0)
                {
                    sb.Append("Indexed Property cannot be used");
                }
                else
                {
                    sb.Append(property.GetValue(this, null));
                }

                sb.Append(System.Environment.NewLine);
            }

            return sb.ToString();
        }

Print Friendly, PDF & Email

Leave a Reply