Thinking Outside The Box


I could really write a few things with that title. As developers we often take the path of least resistance or of most familiarity. Usually this is good because we are using best practices or some other coding standard. Sometimes, these well worn trails are not always the best.

A Simple Task

Like many developers I have had to output data separated by a comma, pipe or something else. I know for a fact I use to hand code putting those strings together. Tedious yes, but at the time it seemed to be the simplest way to go.

Simple and accurate sure, but probably not so smart. We are developers after all, we should make that code work for us! So having to do it another time something hit me. Make a couple static methods to do it for me. I will admit, this is not perfect as it is only addressing the Properties and not Fields. In my particular problem I did not need the fields as the class was just a plain old class of getter/setters. Fourty to be exact. I also did not implement any kind of ordering, so it is based on how you wrote the class as for the order of the properties. It worked great for this case.

My Little Coding Elves

I created two methods for a static helper class. One method will generate a header string and the other will generate a string of the values. The header named and the values are separated using the separator provided to the method.

        public static string CreateHeaderStringForClass(string separator, object oClass)
            string sHeader = String.Empty;
            Type objectType = oClass.GetType();
            PropertyInfo[] props = objectType.GetProperties();
            sHeader = String.Join(separator, props.Select(p => p.Name).ToArray());
            return sHeader;
        public static string CreateDetailStringForClass(string separator, object oClass)
            string sDetail = String.Empty;
            Type objectType = oClass.GetType();
            PropertyInfo[] props = objectType.GetProperties();
            sDetail = String.Join(separator, props.Select(p => p.GetValue(oClass)).ToArray());
            return sDetail;

About SheldonS

Web developer for over 15 years mainly with Microsoft technologies from classic ASP to .NET 4. Husband, father, and aspiring amateur photographer.

Posted on October 28, 2019, in .NET, C# and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: