Click here to Skip to main content
15,883,814 members
Articles / Programming Languages / C#

Objects With Customizable Properties

Rate me:
Please Sign up or sign in to vote.
3.36/5 (8 votes)
25 Apr 2011CPOL4 min read 35.2K   227   26  
A class with customizable properties without using Reflection.
using System;
using System.Collections.Generic;
using System.Text;
using SMoni.ObjectWithProperties.Demo.Classes;
using System.Collections;
using SMoni.ObjectWithProperties.Interfaces;

namespace SMoni.ObjectWithProperties.Demo {
    class Program {

        static void Main(string[] args) {

            useSimplePersonClass();
            useConfigurableClass();
            useForTableResult();
            
            Console.WriteLine("\r\nDone...");
            Console.ReadLine();

        }

        /// <summary>
        /// Using a simple derived class with some properties,
        /// which are all hold in the dictionaries.
        /// 
        /// It is possible to use simple get-set or
        /// per index.
        /// </summary>
        private static void useSimplePersonClass() {

            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
            Console.WriteLine("---------------------------------------------------");

            MySimplePersonClass person = new MySimplePersonClass();

            person.GivenName = "Jane";
            person.Surname = "Doe";
            person.Street = "Unseen";
            person.PostalCode = "123456";
            person.City = "Anywhere";

            person["Addressformat"] = "{GivenName} {Surname}\r\n{Street}\r\n{PostalCode} {City}";

            Console.WriteLine(person.Address);
            Console.WriteLine();

            person["GivenName"] = "John";
            person["Surname"] = "Doe";
            person["Street"] = "Unknown";
            person["PostalCode"] = "56789";
            person["City"] = "Somewhere";

            person["Addressformat"] = "{Surname}, {GivenName}\r\n{Street}\r\n{City} {PostalCode}";

            Console.WriteLine(person.Address);
            Console.WriteLine();

            writeProperties(person);

        }

        /// <summary>
        /// Initially set Properties by use of a dictionary at the creation of an object.
        /// </summary>
        private static void useConfigurableClass() {

            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
            Console.WriteLine("---------------------------------------------------");

            Dictionary<String, Object> firstObjectProperties = new Dictionary<string, object>();
            Dictionary<String, Object> secondObjectProperties = new Dictionary<string, object>();

            firstObjectProperties.Add("Name", "Hello");
            firstObjectProperties.Add("Title", "1st Object");
            firstObjectProperties.Add("A Property", "I'm only in the first object!");

            secondObjectProperties.Add("Name", "Hello");
            secondObjectProperties.Add("Title", "2nd Object");
            secondObjectProperties.Add("Another Property", "I'm only in the second object!");

            MyConfigurableClass firstObject  = MyConfigurableClass.createObject(firstObjectProperties);
            MyConfigurableClass secondObject = MyConfigurableClass.createObject(secondObjectProperties);

            writeProperties(firstObject);

            Console.WriteLine();

            writeProperties(secondObject);

        }

        private static void writeProperties(IObjectWithProperties ObjectWithProperties_) {

            foreach (var property in ObjectWithProperties_.Properties) {
                Console.WriteLine("{0} -> {1}",
                    property.Key.ToString().PadRight(20),
                    property.Value);
            }

        }

        /// <summary>
        /// Using MyConfigurableClass for creating some objects and 
        /// visualize them in a table. The same approach could be used
        /// for a ListView.
        /// </summary>
        private static void useForTableResult() {

            Console.WriteLine("---------------------------------------------------");
            Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
            Console.WriteLine("---------------------------------------------------");

            Dictionary<String, Object> evenObjectProperties = new Dictionary<string, object>();
            Dictionary<String, Object> oddObjectProperties  = new Dictionary<string, object>();

            evenObjectProperties.Add("_Name", "Name of EvenObject");
            evenObjectProperties.Add("_Title", "Even Object");
            evenObjectProperties.Add("1. EvenProperty", "Only Even");
            
            //uncomment for additional properties
            //evenObjectProperties.Add("2. EvenProperty", "Only Even");
            //evenObjectProperties.Add("Common Property", "In Both");

            oddObjectProperties.Add("_Name", "Name of OddObject");
            oddObjectProperties.Add("_Title", "Odd Object");
            oddObjectProperties.Add("1. OddProperty", "Only Odd");
            
            //uncomment for additional properties
            //oddObjectProperties.Add("2. OddProperty", "Only Odd");
            //oddObjectProperties.Add("Common Property", "In Both");

            MyConfigurableClass firstObject  = MyConfigurableClass.createObject(oddObjectProperties);
            MyConfigurableClass secondObject = MyConfigurableClass.createObject(evenObjectProperties);
            MyConfigurableClass thirdObject  = MyConfigurableClass.createObject(oddObjectProperties);
            MyConfigurableClass fourthObject = MyConfigurableClass.createObject(evenObjectProperties);

            firstObject["_Name"]  = "First Object";
            secondObject["_Name"] = "Second Object";
            thirdObject["_Name"]  = "Third Object";
            fourthObject["_Name"] = "Fourth Object";

            List<IObjectWithProperties> list = new List<IObjectWithProperties>();

            list.Add(firstObject);
            list.Add(secondObject);
            list.Add(thirdObject);
            list.Add(fourthObject);

            String[,] arrayWithStrings = createArray(list);

            printArray(arrayWithStrings);
        
        }

        private static String[,] createArray(List<IObjectWithProperties> List_) {

            String[]  columns = getColumns(List_);
            String[,] result  = new String[List_.Count + 1, columns.Length];

            int lineIndex = 1;

            foreach (IObjectWithProperties objectWithProperties in List_) {

                int columnIndex = 0;

                foreach (var column in columns) {

                    result[0, columnIndex] = column;

                    String value = "-";

                    if (objectWithProperties.hasProperty(column))
                        value = objectWithProperties[column].ToString();

                    result[lineIndex, columnIndex] = value;

                    columnIndex++;

                }

                lineIndex++;

            }
            
            return result;

        }

        private static String[] getColumns(List<IObjectWithProperties> List_) {

            List<String> result = new List<String>();

            foreach (IObjectWithProperties objectWithProperties in List_) {
                foreach (var property in objectWithProperties.Properties) {
                    if (!result.Contains(property.Key.ToString()))
                        result.Add(property.Key.ToString());
                }
            }

            return result.ToArray();

        }

        private static void printArray(String[,] lines) {

            Console.WriteLine();

            for (int lineIndex = 0; lineIndex < lines.GetLength(0); lineIndex++) {

                for (int columnIndex = 0; columnIndex < lines.GetLength(1); columnIndex++) {

                    Console.Write(" " + lines[lineIndex, columnIndex].PadRight(20) + "|");

                }

                Console.Write("\r\n");

                Char seperator = '-';

                if (lineIndex == 0)
                    seperator = '=';

                Console.WriteLine(String.Empty.PadLeft(lines.GetLength(1) * 22, seperator));

            }
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Germany Germany
- Born at the dawn of the Video Game Consoles
- Hacked his way through a C64 by Assembler
- Survived the hard times with an Amiga
- Got hit by Delphi on PC in the mid-90s
- Sinned with VB6
- Redeemed by C++ and C#

Comments and Discussions