user4775372
user4775372

Reputation: 87

encapsulation of an array of objects c#

I would like to create an array of objects. Each object has it's own int array. For each object I assign values to it's array ONLY with keys given by myself (example: li[i].V[10] = 1; li[i].V[50] = 10; ) Can someone tell me how to do that? Can I do that without using Lists?

The second case is analogical to first. I would like to know how to assign values of object's List using setter.

I tried to do that by myself. Unfortunately My code crashed cuz I don't know how to set the dimension of V and Word:

class CFiles
{
    //private int[] v=new int[5];//dont want to specify the dimention of array here
    private int[] v;//vector of file
    private List<string> words;
    public CFiles()
    {      
        words = Words;
        v = new int[50];
        v = V;    
    }

    public int[] V { get; set; }
    public List<string> Words { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        CFiles[] li = new CFiles[2];

        for(int i=0;i<li.Length;i++)
        {
            li[i]=new CFiles();

            li[i].V[10] = 1;
            li[i].V[50] = 10;
            li[i].V[50] = 15;

            li[i].Words.Add("a");
            li[i].Words.Add("ab");
            li[i].Words.Add("abc");


        }

        for (int i = 0; i < li.Length; i++)
        {
            for(int j=0;j<li[i].V.Length;j++)
            {
                Console.WriteLine(li[i].V[j]);
            }
        }

        Console.WriteLine();

    }
}

Upvotes: 0

Views: 1280

Answers (1)

d512
d512

Reputation: 34103

Your constructor isn't right and your properties aren't quite right. You might want something more like this:

class CFiles
{
    //private int[] v=new int[5];//dont want to specify the dimention of array here
    private int[] v;
    public int[] V { get { return v; } set { v = value; } }

    private List<string> words;
    public List<string> Words { get { return words; } set { words = value; } }

    public CFiles()
    {
        words = new List<string>();
        v = new int[51]; //needs to be 51 if you are going to assign to index 50 below
    }
}

Other than those issues, your code seems to do what you want. You have an array of objects where each object has its own int array (in addition to a string of strings).

Is that not what you want?

Upvotes: 1

Related Questions