Hello,
I've encountered a problem.
I've a class that looks like this: - public class student
-
{
-
public int number;
-
public string surname;
-
public string[] subjects = new string[10];
-
};
The objects of the class are then added to a list - List<student> students = new List<student>();
- students.Add(new student
-
{
-
number = counter1,
-
surname = textBox1.Text,
-
subjects = choice
-
});
while - choice[0] = listView1.Items[counter1].SubItems[1].Text;
-
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?
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. - public class Student
-
{
-
...
-
private List<string> m_subjects = new List<string>();
-
-
public Subjects { get { return m_subjects; } }
-
...
-
}
- Student newStudent = new Student()
-
{
-
Students.AddRange(choice)
-
};
-
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... - for (int i = 0; i < choice.length; i++)
-
newStudent.Subjects.Add(choice[i]);
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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>
|
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...
|
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
|
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...
| |
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,
|
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()
|
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"
|
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
|
by: Gangreen |
last post by:
I have something like:
Class A{
...other variables and methods...
/*
* PRIVILIGES
*/
public function getPriviliges(){
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
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...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |