0

My question is how do I change the following code to create 10 different instances of objects instead of 10 of the same Object.

 List <OBJ> newList = new List<OBJ> ();
 for (int i = 0; i < 10; i++){
     OBJ newOBJ = new OBJ (i);
     newList.Add(newOBJ);  
 }

Where the OBJ class is:

 class OBJ    {
    public static int numb;

    public OBJ(int i)
    {
        numb = i;
    }
}
2
  • 2
    Whats the purpose of numb being static? Commented Aug 21, 2012 at 14:15
  • No reason, it's a bug. And no this is not homework. Commented Aug 21, 2012 at 14:19

7 Answers 7

8

That are 10 different objects. But since the number is static, they all have the same number.

So make it non-static if you want.

class OBJ    {
    public int numb;

    public OBJ(int i)
    {
        numb = i;
    }
}

If you want to count the number of instances, you can leave it as static.

class OBJ    {
    public static int num_instances;
    public int number;

    public OBJ(int i)
    {
        number = i;
        num_instances ++;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3

Make numb an instance field instead of a class field. Remove the static:

public int numb;

When static all instances of OBJ use the same int named numb.

1 Comment

Thanks, I can't believe I missed that.
2

That is what your code is doing already. the static keyword on your numb member makes numb shared across all instances of OBJ.

Comments

2

I'm not sure that i understand your question but try remove the static keyword.

Comments

2

Anytime you use new, you get a new instance. The code seems ok. The only problem is that you should REMOVE static from public static int numb.

class OBJ    {
  public int numb;

  public OBJ(int i)
  {
      numb = i;
  }
}

Comments

1

You are creating new instances, but your only property is static which gets shared among all instances.

Comments

0

You should only remove the static keyword...take a look to this: http://msdn.microsoft.com/en-us/library/98f28cdx(v=vs.100).aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.