Attach to Process

CSharp

If you've ever needed to get a list of the base classes/types for an object in C#, this is one way of doing it. In my case, I had an object which was of the base class/type, but it was really a derived type.

Example: I had an object of type Animal, but it was really an instance of the Dog class, which is derived from the Animal base class.

The beauty of inheritance in object oriented programming is that the current instance of the object, can be an instance of the derived type, or the base type; it doesn't matter. As long as the code expects you to provide it an object of the base type, you can provide an instance of either one.

I needed to record the type hierarchy for that object when saving it to the database. So this utility method is what I came up with in short order. I am returning a list of strings in my example below, but there is nothing stopping you from returning an array of Types or whatever else you may need based on your scenario.

private List<string> GetTypeHierarchy()
{
    List<string> typeHierarchy = new List<string>();

    Type currentType = this.GetType();
    typeHierarchy.Add(currentType.Name);

    Type baseType = currentType.BaseType;
    while (baseType != null)
    {
        typeHierarchy.Add(baseType.Name);
        baseType = baseType.BaseType;
    }

    typeHierarchy.Reverse();
    return typeHierarchy;
}

I intentionally wrote this without recursion, because recursion hurts my head haha. There might be a better/cleaner way of doing this, if so, do share your solution with me.

#CSharp #DotNet

Discuss... or leave a comment below.

Out of the 5 SOLID principles, the Open/Closed principle was the hardest one for me to grasp. This post from Code Maze explains it really well and the code examples were very helpful. This was a good read.

Link: Open and Closed Principle

Rather than writing my own post about it, I thought I would share this one instead. After all, as programmers we should avoid reinventing the wheel as much as possible. This is also my first post in a new “Bookmarks” category that I've added to this website. The plan is to use that new post category to share interesting articles that I've found online.

#Bookmarks #SolidPrinciples #CSharp

Discuss... or leave a comment below.