generically-parse-data-from-strings-for-child-class

CSharp · Console

/Program.cs

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

public class Program
{
	public static void Main()
	{
		Console.WriteLine("childClassOne");
		var cc1 = new childClassOne();
		Console.WriteLine("\nchildClassTwo");
		var cc2 = new childClassTwo();
	}

	abstract public class containerClass
	{
		protected containerClass()
		{
		    // do stuff
		}
		        
		protected Comparison<PropertyInfo> comparer = (x,y) => {
			var type = typeof(ProperyOrderAttribute);
            var xAttr = x.GetCustomAttributes(type, false);
            var yAttr = y.GetCustomAttributes(type, false);
            var xOrder = xAttr.Count() > 0 ? 
				(xAttr[0] as ProperyOrderAttribute).Order : 
			Int64.MaxValue;
            var yOrder = yAttr.Count() > 0 ? 
				(yAttr[0] as ProperyOrderAttribute).Order : 
			    Int64.MaxValue;
            return xOrder.CompareTo(yOrder);
        };		

		virtual protected void parseData()
		{
			var properties = this.GetType().GetProperties();
		
			// maintain the order
			Array.Sort(properties, comparer);
			
			// iterate through the properties when it's called by a child class
			foreach (var p in properties)
			{
				// and parse the strings for relevant data
				var propName = p.Name;
				var propValue = p.GetValue(this);
				Console.WriteLine(string.Format("{0} = {1}", propName, propValue));
			}
		}
	}

	[System.AttributeUsage(System.AttributeTargets.Property)]
	public class ProperyOrderAttribute : System.Attribute
	{
		public int Order
		{
			get;
			private set;
		}

		public ProperyOrderAttribute(int order)
		{
			this.Order = order;
		}
	}

	public class childClassOne : containerClass
	{
		public childClassOne(): base ()
		{
			var1S = "99";
			var2S = "88.3";
			var3S = "2015-04-22T15:55:25.2625065-07:00";
			parseData();
		}

		[ProperyOrderAttribute(0)]
		public int var1
		{
			get;
			protected set;
		}

		[ProperyOrderAttribute(1)]
		public double var2
		{
			get;
			protected set;
		}

		[ProperyOrderAttribute(2)]
		public DateTime var3
		{
			get;
			protected set;
		}

		[ProperyOrderAttribute(3)]
		public string var1S
		{
			get;
			protected set;
		}

		[ProperyOrderAttribute(4)]
		public string var2S
		{
			get;
			protected set;
		}

		[ProperyOrderAttribute(5)]
		public string var3S
		{
			get;
			protected set;
		}
	}

	public class childClassTwo : containerClass
	{
		public childClassTwo(): base ()
		{
			var1S = "99.22";
			var2S = "88.3";
			var3S = "43.44";
			parseData();
		}

		public double var1
		{
			get;
			protected set;
		}

		public double var2
		{
			get;
			protected set;
		}

		public double var3
		{
			get;
			protected set;
		}

		public string var1S
		{
			get;
			protected set;
		}

		public string var2S
		{
			get;
			protected set;
		}

		public string var3S
		{
			get;
			protected set;
		}
	}
}
;