SimpleHelpers.Net icon indicating copy to clipboard operation
SimpleHelpers.Net copied to clipboard

Object2String Generator

Open LordPinhead opened this issue 5 years ago • 1 comments

Hi, i like the DiffPatch Generator, makes a lot of work for me. As for a Simple Helper i use many times:

using System;
using System.Linq;
using System.Reflection;
using System.Text;

#pragma warning disable CS1591
namespace Helper {
	public sealed class Object2String<T> : IObject2String<T> {
		public string ToString(T obj) {
			StringBuilder toReturn = new StringBuilder($"{obj.GetType().Name} -> ");
			var publicPropertys = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
			var primitivePropertys = publicPropertys.Where(prop => prop.PropertyType.IsPrimitive || prop.PropertyType.IsValueType || prop.PropertyType == typeof(string)).ToList();
			var nonPrimitivePropertys = publicPropertys.Where(prop => !(prop.PropertyType.IsPrimitive || prop.PropertyType.IsValueType || prop.PropertyType == typeof(string))).ToList();

			primitivePropertys.ForEach(prop => toReturn.Append($"{prop.Name}: {prop.GetValue(obj)?.ToString()} "));
			nonPrimitivePropertys.ForEach(
				prop => {
					if (prop.GetValue(obj) != null)
						toReturn.Append($"| {prop.GetValue(obj)?.ToString()} ");
					}
				);

			return toReturn.ToString().Substring(0, toReturn.ToString().Length - 1);
		}
	}
}
#pragma warning restore CS1591

Should i put an Pull Request or is it "too simple" for you :)

LordPinhead avatar May 28 '19 13:05 LordPinhead

Hi @LordPinhead sorry for the late reply. I loved to hear that you are making good use of this code :) Yes, a PR would be nice. best!

khalidsalomao avatar Oct 17 '19 19:10 khalidsalomao