1

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?


1 Answers1

1

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • You answer is much higher quality than the one i compose. I still want to thank [mjwills](https://stackoverflow.com/users/34092/mjwills) who directed me to the right answer [here](https://stackoverflow.com/a/5768449/5757162) bevor you answerd it :) – Squirrel in training Jul 28 '17 at 13:56