How to add a property to an object you can’t change?

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; }
    }
}

1

The best answer is you shouldn’t. But if you don’t mind a performance overhead, you can do something similar with ConditionalWeakTable<,>:

public static class ExtraFruitProperties
{
    private static readonly ConditionalWeakTable<Fruit, Color> _colors = new ConditionalWeakTable<Fruit, Color>();

    public static void SetColor(this Fruit @this, Color color) 
    {
         _colors.Remove(@this);
         _colors.Add(@this, color);
    }

    public static Color GetColor(this Fruit @this) 
    {
         Color color;
         if(_colors.TryGetValue(@this, out color)) return color;
         return default(Color);
    }
}

4

You don’t.

The closest you can get to is Java style properties via extension methods, though if you actually need to store the color (as opposed to map it in the function) it can be difficult to do correctly since the extension class would hold references to the actual class if you do it the naive way.

The alternative is using standard inheritance or composition to extend the class, which you already mentioned.

Use a separate hash table to add properties to objects you don’t control, and use
your own access functions to wrap whatever behavior you want to appear to be uniform
with respect to your added properties.

If garbage collection is likely to be a concern (your extra properties implemented
this way will prevent the object from being garbage collected) this is perhaps the
only good use of weak eq hash tables.

I don’t see what’s so “awful” about your last solution. You’re given a definition of a Fruit, but you want it to be more descriptive. So you define an extension of the original definition with your Color addition.

Really, why do you prefer:

    Person.Fruits.FirstOrDefault().Color 

over:

    MyPerson.MyFruits.FirstOrDefault().Color

Only difference is the ‘My’ prefix which is purely cosmetic. You could also have a more descriptive name like ColoredFruit.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật