Roffers
Roffers

Reputation: 701

Set the properties of a base class in c#

I have what I think is a simple noob question.

In the CMS i'm using there's a method Product.Get(4545) which get's all the properties for the built in Product class.

I wish to extend the product class with this, so I guess this is what I would do on at basic level.

public class ExtendedProduct : Product
{
    public ExtendedProduct ()
    {

    }

    public string Foo { get; set; }
}

But how do I set the base product to be the result of Product.Get(4545) so all those properties are set? I was thinking something like (and this doesn't work) base = Product.Get(4545) or similar.

The Product class has literally 100s of properties already in it. For example.

I could call

var prod = Product.Get(22);
var price = prod.Price; //22.99

Updating my thoughs from from the responses below, I was thinking of

var prod = ExtendedProduct.Get(22); static method that sets the base class properties?
var price = prod.Price; //22.99
var foo  = prod.Foo

Whilst writing this I think the easiest thing is to pass Product into the contstructor of ExtendedProduct and have a property of Product. But is that being lazy?

I was hoping to avoid a scenario where I would call new ExtendedProduct(product).Product.Price and just call new ExtendedProduct(product).Price

public class ExtendedProduct
{
    public ExtendedProduct (Product product)
    {
        this.Product = product;
    }
    
    public Product Product { get; internal set; }

    public string Foo { get; set; }
}

Upvotes: 0

Views: 823

Answers (1)

John Wu
John Wu

Reputation: 52210

Pretty hard to do exactly what you want. I suggest reversing it instead. Retrieve the regular Product object the normal way, and use an extension method to convert it to the extended object as needed.

static class ExtensionMethods
{
    static public ExtendedProduct ToExtendedProduct(this Product source)
    {
        return new ExtendedProduct(source);
    }
}

Now you can do this:

var prod = Product.Get(22); 
var price = prod.Price; 
var foo  = prod.ToExtendedProduct().Foo;

Upvotes: 1

Related Questions