- PlayerStatus ps;
-
PlayerStatus ps1 = new PlayerStatus();
-
ps = ps1; //<-
This code causes compilation errors. Help me please to fix it.
Invalid token ';' in class, struct, or interface member declaration (CS1519) - C:\Users\user1\Documents\SharpDevelop Projects\v2\v2\MainForm.cs:18,11
Invalid token '=' in class, struct, or interface member declaration (CS1519) - C:\Users\user1\Documents\SharpDevelop Projects\v2\v2\MainForm.cs:18,6
Another question: when i pass to a method class-argument, does method duplicate original argument, or uses a pointer to a real object? 8 1727 GaryTexmo 1,501
Recognized Expert Top Contributor
The problem might be in your PlayerStatus class... there shouldn't be anything wrong with the three lines of code you posted. Can you declare and use a variable of type PlayerStatus without the ps = psl?
For your second question, there's a bit of trickyness here. For the most part, it does pass the reference to your object along... here's an example using a list of strings. - private void SomeMethod()
-
{
-
List<string> test = new List<string>();
-
DoSomething(test);
-
-
if (test != null && test.Count > 0)
-
{
-
foreach (string str in test)
-
{
-
Console.WriteLine(str);
-
}
-
}
-
else
-
{
-
Console.WriteLine("List is empty!");
-
}
-
}
-
-
private void DoSomething(List<string> list)
-
{
-
list.Add("item1");
-
list.Add("item2");
-
list.Add("item3");
-
list.Add("item4");
-
list.Add("item5");
-
}
In this example, the list will contain the items that were added in the method. However, if you change the DoSomething method to... - private void DoSomething(List<string> list)
-
{
-
list = new List<string>();
-
list.Add("item1");
-
list.Add("item2");
-
list.Add("item3");
-
list.Add("item4");
-
list.Add("item5");
-
}
The list in SomeMethod won't be changed to the new one you created in DoSomething. In order to make this work, you need to explicitly pass the reference to test by doing the following... - private void DoSomething(ref List<string> list)
I can tell you that this is how it works, but I can't tell you why... I've just discovered this recently and frankly, it confuses me. Hopefully someone else on this forum can explain why we can pass an existing list and modify it in a method, but if we create a new instance of an object in a method it doesn't get passed back out.
*Edit: After doing some googling, I think I understand why this is the case now. Per this MSDN article...
A variable of a reference type does not contain its data directly; it contains a reference to its data. When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref (or out) keyword.
I can tell you that this is how it works, but I can't tell you why... I've just discovered this recently and frankly, it confuses me. Hopefully someone else on this forum can explain why we can pass an existing list and modify it in a method, but if we create a new instance of an object in a method it doesn't get passed back out.
Maybe this is because the compiler confuses argument with local variable (same name) ?
Can you declare and use a variable of type PlayerStatus without the ps = psl?
Yep, this works okay.
So, this is my class, you say? There's nothing special about it, actually.
I have one more class (WorldMap) which uses the "problematic" PlayerStatus class. The PlayerStatus itself is primitive.
okay, i've found it:
i had to move this code inside method to get rid of the errors.
it's an old lame mistake i make every time =)))
cloud255 427
Recognized Expert Contributor
Hi,
This is really all about deep and shallow copies, which C# doesn't handle as well as an unmanaged language such as C++.
The accepted solution to this problem is to have your class inherit from IClonable.
In your implementation of the Clone() method you should perform binary serialization of the the object, de-serialize it and return the de-serialized object. Not very elegant is it?
When you want a deep copy of your object you can then simply call the Clone method: - PlayerStatus ps;
-
PlayerStatus ps1 = new PlayerStatus();
-
ps = ps1.Clone(); //ps is now a deep copy of ps1
As for passing by reference and value:
When you pass a parameter by value, the changes to that variable will only be in effect for the scope of the method. This is kind of like a new instance is created inside the method and is assigned the value of the parameter.
When passing by reference you actually pass a pointer to the object. So any changes made to the object will also happen in the scope from where the function call was made. The variable never 'leaves' the original code block, the method is simply given access to alter the variable's memory block.
See the below code for a more concrete idea: - void MainFormLoad(object sender, EventArgs e)
-
{
-
int x = 0;
-
byValue(x);
-
MessageBox.Show("Original Object: " + x.ToString()); //x is still 0
-
-
byReference(ref x);
-
MessageBox.Show("Original Object:" + x.ToString()); //x is now 5
-
}
-
-
void byValue(int value)
-
{
-
value += 5;
-
MessageBox.Show("Inside value function: " + value.ToString());
-
}
-
-
void byReference(ref int value)
-
{
-
value += 5;
-
MessageBox.Show("Inside reference function: " + value.ToString());
-
}
I'm not too good at explaining stuff like this... forgive me if it is incoherent.
cloud255
From now on, I'm going to use ref keyword intensivly, although, programm worked well anyway. I'll save lots of memory =)))) - void byReference(ref int value)
ref has to appear not only in method prototype, but also in method call, right? This is what compiler says))))
----
Interesting code. - ps = ps1.Clone(); //ps is now a deep copy of ps1
Actually, I only needed ps to be a reference/pointer, not copy the whole variable into ps.
GaryTexmo 1,501
Recognized Expert Top Contributor
It may have gotten missed because it was at the bottom of an admittedly long, long post (sorry!) but yea I found the answer to my confusion at the following MSDN page. This page also explains your question about ref, EntryTeam. I hope it helps, I know it helped me!
Also, what was the solution? You didn't really post enough code for me to get the context of what changed... I'm curious as to how you solved it :)
2 GaryTexmo
Also, what was the solution? You didn't really post enough code for me to get the context of what changed... I'm curious as to how you solved it :)
The error was appearing, 'cause this code was placed outside any method. I had this kind of errors before, just forgot 'bout it. @EntryTeam
P.s.:
It may have gotten missed because it was at the bottom of an admittedly long, long post (sorry!) but yea I found the answer to my confusion at the following MSDN page.
It's my mistake, I posted reply before I finished reading your post ;)
Thank you a lot for answering, GaryTexmo and cloud255. MSDN also appeared to be pretty helpful.
GaryTexmo 1,501
Recognized Expert Top Contributor
Oh sorry for not being clear, I just meant I didn't understand how that was your solution... I think I do now :)
Anyway, glad you got it resolved!
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: William Payne |
last post by:
In the following code, should the code compile without casting &n to void* ?
My compiler accepts it, but should it?
void foo(void*)
{
}
struct bar
{
int n;
|
by: Daren Fox |
last post by:
I am writing an application that will require new commands to be added while
the program is still running. I thought I had found the answer in .nets
compiler facilities. I would seperate my...
|
by: Martin Jørgensen |
last post by:
Hi,
I don't understand these errors I get:
g++ Persort.cpp
Persort.cpp: In function 'int main()':
Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping
Persort.cpp:37:...
|
by: wong_powah |
last post by:
#include <vector>
#include <iostream>
using std::cout;
using std::vector;
enum {DATASIZE = 20};
typedef unsigned char data_t;
|
by: desktop |
last post by:
I have read that using templates makes types know at compile time and
using inheritance the types are first decided at runtime. The use of
pointers and casts also indicates that the types will...
| |
by: Dameon99 |
last post by:
Hi, when i try to compile my code it comes up with two errors both in the same function.
The errors are both the same:
106assig-4.cpp invalid conversion from `void*' to `int**'
Here is my...
|
by: Tomás Ó hÉilidhe |
last post by:
I've been developing a C89 microcontroller application for a while
now and I've been testing its compilation using gcc. I've gotten zero
errors and zero warnings with gcc, but now that I've moved...
|
by: beet |
last post by:
Hi,
I am really not good at c/c++.
Some simple code..
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "simlibdefs.h"
|
by: Andrus |
last post by:
I need compile in-memory assembly which references to other in-memory
assembly.
Compiling second assembly fails with error
Line: 0 - Metadata file 'eed7li9m, Version=0.0.0.0, Culture=neutral,...
|
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...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
| |
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: 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...
|
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...
|
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,...
|
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...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |