473,809 Members | 2,849 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Objects inside a class getting overwrited?

8 New Member
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 1347
GaryTexmo
1,501 Recognized Expert Top Contributor
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
1458
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 Private strName As String Private strSSN As String Private strDOB As String Private myMugshotPicture() As MugshotPicture End Class
1
2949
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 is a member of the same class it is working fine. Here is my .h file #include <wtypes.h>
3
1314
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 that being that when i have multiple objects present in the union, it gets confused as to whose constructor to call. One way I got around that was to wrap those objects with anonymous structs. I was wondering if this was a standard way of doing it...
1
1551
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
1040
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 created, it creates a connection to the database. My initial plan was that, at the very top of each page I would: 1) include the DBClass class file, so the page knows about the class 2) create an instance of DBClass, which I call DB. My thought...
5
11328
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 always optimize and turn it into a static const variable to save runtim memory/stack space since being const it cannot be changed. (?) Thanks,
1
1116
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 I can't access the parent object from the seccond one. Is something like this: function B() { this.send_alert = function() { alert(this.parent); } } function A()
7
8529
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 here" def func1(): print "hello"
8
2458
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 the value is a pointer to another map. I do new of std::map<std::string, std::stringand add the pointer to the map. Do I have to delete the map objects which I create with new , which I
1
1766
by: Gangreen | last post by:
I have something like: Class A{ ...other variables and methods... /* * PRIVILIGES */ public function getPriviliges(){
0
9722
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10378
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10391
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10121
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9200
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.