Search code examples
c#generic-programming

Accesing a Class.Name property from diffrent classes without inheritance


I am trying to write a Method that uses the Name property of diffrent classes and does some logic with it.

In my exampel to keep it simple i will restrict myself to simply returning the Name value:

class Dog
{
    public string Name { get; set; }
}

class Human
{
    public string Name { get; set; }
}

/*
 ...
*/

public string GetNameFromNameProperty(object obj)
{
    return obj.Name;
}

Sadly the classes are not inherting from a parent class that has the Name property. Furthermore it is not possible to implement that or add an interface.


Short Recap:
Is it possible to write a generic Method that uses a Name property without being sure that the class has implemented that property?



Solution

  • If you really don't want to make all those classes implement a common interface or inherit from a base class, then here are two options:

    Reflection:

    public string GetNameFromNameProperty(object obj)
    {
        var type = obj.GetType();
        return type.GetProperty("Name").GetValue(obj) as string;
    }
    

    Dynamic Binding:

    public string GetNameFromNameProperty(dynamic obj)
    {
        try
        {
            return obj.Name;
        }
        catch (RuntimeBinderException)
        {
            throw new PropertyDoesntExistException();
        }
    }
    

    You can also choose to return null if the property does not exist.

    However, I strongly advise you to use interfaces or inheritance to do this. You basically lose all the type-safety that C# provides if you used the above methods.