0

It seems like this question gets asked frequently, but having looked through all of them, I find I'm still without aid. I'm taking my first step into oop, and I need to create an object with an attribute "Products" that is an array of up to 7 possible objects of class "Product". I just just barely understand the {get;set;} method, and am reading up on it, but I was hoping I could get some help with the syntax of what I'm trying to do here. I'm using C#. My code is below:

public class Submission 
{

    public Submission() {}
    public int SubmissionId {get;set;}

    public int CustId {get;set;}

    public int BroId {get;set;}

    public int Coverage {get;set;}

            public Array Products // what goes here? It's a mystery. 
} 

4 Answers 4

1

In this case, I think you don't want an auto-implemented property. Instead, do it like this:

//backing store for your public property
private Product[] _products = new Product[7];

public Product[] Products { get {return _products;}}

and then in the constructor:

foreach(var item in _products) {item = new Product(); }

You could do this with a private setter rather than an explicit backing store, but I think this way is easier as far as setting up the size of the array goes.

Notice that I only provided a getter for the property. You don't want a setter, as that would allow someone to replace your property with a whole new array. Just providing a getter will still allow someone to manipulate the property. Also, normally I would recommend a collection rather than an array for this, but since you want a fixed-size for the number of items an array might be a better fit.

Sign up to request clarification or add additional context in comments.

2 Comments

Any reason why you'd prefer an explicit backing field rather than simply having a private setter?
@Anthony - because of the [7] in the backing store. I'd use a private setter for lists and other collections. 6 of 1, 1/2 dozen of the other, really.
1

If you are up to using generic collections, I would use:

 public List<Product> Products { get; private set; } 

or some variation thereof.

2 Comments

You probably don't want a setter for this property.
Probably not. Updated to reflect as such.
0

You can write it like this:

public Products[] { get; set; }

and in the constructor of your class:

public Submission() { Products = new Product[7]; }

Comments

-1

Use an IList. You can use the auto property with it.

1 Comment

Why was the IList downvoted? I saw Joel suggested it first, and then edited to another method. Any reason an IList is a bad idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.