473,387 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Objects inside a class getting overwrited?

Hello,
I've encountered a problem.

I've a class that looks like this:
Expand|Select|Wrap|Line Numbers
  1. public class student
  2.         {
  3.             public int number;
  4.             public string surname;
  5.             public string[] subjects = new string[10];
  6.         };
The objects of the class are then added to a list
Expand|Select|Wrap|Line Numbers
  1. List<student> students = new List<student>();
Expand|Select|Wrap|Line Numbers
  1. students.Add(new student
  2.             {
  3.                 number = counter1,
  4.                 surname = textBox1.Text,
  5.                 subjects = choice
  6.             });
while
Expand|Select|Wrap|Line Numbers
  1. choice[0] = listView1.Items[counter1].SubItems[1].Text;
  2.             choice[1] = listView1.Items[counter1].SubItems[2].Text;
etc.

My problem is that, when I add two students, and let's say, I set English on Higher Level on the first one and on Standard Level on the second one, the choice of the first one is getting overwrited. As such, both take the value "Standard Level". Any ideas on how may I fix this? May I somehow lock the items inside the list to make them non-changeable upon addition?
Feb 23 '12 #1
1 1337
GaryTexmo
1,501 Expert 1GB
The thing to remember about C# is that almost everything is a reference type. In fact, the only things that aren't are the primitive types, such as int, double, float, string, bool, and struct. Anything else, the instantiation of a class, an array, etc... is a reference. Meaning all the variable holds is an address to allocated memory.

So in your case, your subjects member in your student object is a string array. When you create a new student, you assign in to an existing string array (thus overwriting what you initialized). Now your student's subject member points to the choices object. If you create two students and assign both their subjects to choices, both of those students have their subjects looking at the same object. You then modify the choices object which changes both student objects.

Hopefully that makes sense.

Anyway, you need to make sure that students contains it's old objects if you want it to maintain a unique list of subjects. This means you'll need to copy the choice data... My recommendation would be to change the subjects type to a List<string> instead of a fixed size string array. Then you can add each item in your choice array into that, creating a copy.

Expand|Select|Wrap|Line Numbers
  1. public class Student
  2. {
  3.   ...
  4.   private List<string> m_subjects = new List<string>();
  5.  
  6.   public Subjects { get { return m_subjects; } }
  7.   ...
  8. }
Expand|Select|Wrap|Line Numbers
  1. Student newStudent = new Student()
  2. {
  3.   Students.AddRange(choice)
  4. };
  5. students.Add(newStudent);
Note that the AddRange method on a List<T> takes a T[] (T stands for any type) parameter, which is an array. This is equivalent to doing...

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < choice.length; i++)
  2.   newStudent.Subjects.Add(choice[i]);
Feb 23 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: CLEAR-RCIC | last post by:
How would I create an array of objects inside a class? When I do it the following way I get an error that says: 'Object reference not set to an instance of an object'. Public Class Inmate...
1
by: Venkat | last post by:
Hi All, I am getting unusual compile errors when i declare a vector as a private member of a class in .h file, but if i declare the same in .cpp file inside the definition of a function which...
3
by: Deepak | last post by:
Hi all, I am trying to create a union consisting of objects whose classes have default constructors, destructors etc. The compiler however doesn't allow me to do that, the reason I believe for...
1
by: steven scaife | last post by:
Hi I have created a class that inherits from dictionarybase code below. Public Class FrmLabels Inherits Label Private m_Lbl As Label Public Property lbl() As Label Get Return m_Lbl End Get
2
by: Greg Stevens | last post by:
Here is the situation. I'm developing an application where: I have defined a class (DBClass) to provide an abstraction layer for interacting with a database. When an instance of the class is...
5
by: John Goche | last post by:
Hello, I would like to know whethere there is a difference between a const variable and a static const variable inside a class. After all, if a variable is const in a class, the compiler can...
1
by: joefraga | last post by:
Hi I have a javascript "class" that generates some html and handle some events and so. I want to have a "sub class" (an instance of an object) that is a child of the first one. The problem is that...
7
by: beginner | last post by:
Hi Everyone, I have encountered a small problems. How to call module functions inside class instance functions? For example, calling func1 in func2 resulted in a compiling error. "my module...
8
by: jayaramganapathy | last post by:
Hello friends, I have a map like std::map< std::string , std::map<std::string, std::string>* EpPropCache::propertyCache ; (This is a static instance and taken from *.cpp file) As you can see...
1
by: Gangreen | last post by:
I have something like: Class A{ ...other variables and methods... /* * PRIVILIGES */ public function getPriviliges(){
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.