SimpleHelpers.Net
SimpleHelpers.Net copied to clipboard
Object2String Generator
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 :)
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!