Let's say that I'm using a library and I would like to add a property that doesn't exist to an existing class. In this case, I'd like to add Color as a property of Fruit.
namespace Library
{
public class Fruit : System.IDisposable
{
public string Name { get; set; }
public void Dispose() { }
}
}
Is there any way to do that in C#?
Example that won't work
My first thought was partial classes but that would require that both classes would have the word partial in them. So that's not doable.
namespace Library
{
public partial class Fruit
{
public Color Color { get; set; }
}
}
This seems awful
I could inherit Fruit and create a MyFruit class. This seems clunky to me. I'd much rather call Person.Fruits.FirstOrDefault().Color than to have to create a MyPerson object that inherits from Person and then call MyPerson.MyFruits.FirstOrDefault().Color.
namespace Library
{
public class MyFruit : Fruit
{
public Color Color { get; set; }
}
}
namespace Library
{
public class MyPerson : Person
{
public MyFruit MyFruit { get; set; }
}
}
Person.Fruits.OfType<MyFruit>().FirstOrDefault()
should be all you need, rather than creating a hierarchy somewhere else. Something which takesFruit
naturally takesMyFruit
. – Magus May 1 '15 at 22:22