I have a class. I have two instance member variables x and y, and the class also has a function which again takes two variables named x and y.
public class MyClass
{
public int x;
public int y;
public int Add(int x , int y)
{
return (x + y);
}
}
Now I am creating an instance of the class and assigning the values to the instance variables and If I call the function using the same instance the value of the instance variables is getting changed to the values which I am passing as parameter to the function as shown below
MyClass abs = new MyClass();
abs.x = 10;
abs.y = 11;
Console.WriteLine(abs.Add(12, 13).ToString());
While debugging I found that the value of instance variables is changed to 12 and 13 respectively. Why is it so? What exactly is happening.
I'm sure the instance fields are not changed. Most likely you misinterpreted your debugger output. If you simply watch x or y while you are in the Add method the debugger (watch window) will show the values of the method parameters. You need to watch this.x or this.y.
That's also one of the reasons why I always start my instance fields with a underscore.
Well it should not change and the best way to confirm would be add this too
Console.WriteLine(abs.Add(12, 13).ToString()); // output 25
Console.WriteLine(abs.x + abs.y); // output 21
to check the value of the field you need to use this.x
For more details Variable names should not match field names
Debugger shows the x value for the scope in which the break point is located. Pointing the member declaration with mouse does not necessarily required to show that variable's value. Check this.x in watch view.
Related
I am having a problem assigning values in my function. Here is my code
//Player cents
private int add_cents = 3;
public int player_1, enemy_1, enemy_2, enemy_3;
public void players_ready()
{
add_cents_player(player_1, add_cents);
}
public void add_cents_player(int player, int cent_v)
{
player = player + cent_v;
}
I want to be able to call this function and input whoever is the active player (player) and increase their value by (cent_v). However, player = player + cent_v; is saying "Unnecessary assignment of a value to 'player" and I don't understand why. It wouldn't be possible to hard code, as it is dependant on what who is the active player.
One option is to change the method return type:
private int add_cents = 3;
public int player_1, enemy_1, enemy_2, enemy_3;
public void players_ready()
{
player_1 = add_cents_player(player_1, add_cents);
}
public int add_cents_player(int player, int cent_v)
{
return player + cent_v;
}
int is a value type. It is passed by value meaning the player will actually be a copy of player_1. If you then change the player inside your method this doesn't affect in any way the player_1 since it is no reference and no relationship between them.
It looks like what you wanted to do would be using ref in order to "force" the value to be passed by reference
public void players_ready()
{
add_cents_player(ref player_1, add_cents);
}
public void add_cents_player(ref int player, int cent_v)
{
player += cent_v;
}
thus that after calling players_ready the value player_1 is actually increased
There are 2 ways to pass a variable to a function. 1 is by reference, meaning you pass a reference to a variable into the function. This is what happens with variables of type object - not the whole object's memory is copied and supplied to the function, but only an address to the piece of memory where that object resides.
For int, float etc. this is different. The values are passed by value.
Also see the relevant msdn docs.
There is a fundamental difference between the two options: reference types are passed by reference and can be altered and the original object also gets altered. E.g. this works:
class MySimpleObject // an object is a reference type
{
public int someValueType; // int is a value type
}
...
var x = new MySimpleObject();
myFunc(x); // increment x.someValueType by 5
This does not count for objects passed by value, which is what happens with int, as its a value type. Therefore your function does nothing, because its only manpulating the local value, the reference is not passed.
var player_1 = 5;
add_cents_player(player_1, 15);
// Player_1 is still 5
add_cents_player(player_1, 15);
// Player_1 is still 5
...
And thats what the compiler is complaining about; you're adding a value to the local parameter in the function. But since you don't return this, or read the value at some point the compiler is like 'hey this code does nothing, and therefore its better to remove it.
I started my journey with C# but I realised that I have some problems with some basic information about memory when it comes to declaration of variables. See if I am correct.
int x; // I declared variable of type int, which name is x. Compiler will provide memory for it but we dont have known value of it.
x=10; // Now memory location is still the same but value now kept there is 10;
public struct Point {
public int x, y;
}
Now I define a struct named Point. Beacuse struct is a value type, it again has reserved memory for it on the computer. Howewer x and y have no value.
Now Point p1 = new Point(); // what is happening here? Struct is not a reference type. So is this just initialization of Point variable with the default constructor without assigning values to x and y?
Second short question. When I write a code like:
int x = 10;
Can I say that I created instance of class integer which value is 10 and name x;
I would be grateful for help.
// what is happening here? Struct is not a reference type. So is this just initialization of Point variable with the default constructor without assigning values to x and y?
No; there are 4 possible scenarios here:
a class: the memory space is wiped to all 0s, then any custom constructor is invoked, which may also involve field initializers
a struct called without a custom constructor: the memory space is wiped to all 0s
a struct called with a custom constructor: the custom constructor is required to assign all the fields
a struct variable used without ever calling a constructor: this is actually a thing, but the calling code must write to all the fields before they can do anything else with it; since most structs do not expose their fields, this rarely works
Second short question. When i write a code like:
int x = 10;
Can i say that i created instance of class integer which value is 10 and name x; I would be grateful for help.
Not really, because in C# terms, int is not a class (it might be in IL terms). Simply: you have declared a local variable of type int with name x and assigned it the value 10, if this is in a method. If this is a class field, then: you have declared a private instance field of type int named x with a field-initializer giving it the value of 10.
Incidentally, you should avoid public fields in general, and mutable fields on structs. You might prefer:
public struct Point {
private readonly int x, y;
public int X { get { return x; } }
public int Y { get { return y; } }
public Point(int x, int y) { this.x = x; this.y = y'; }
}
This will avoid a huge range of problems.
In C# the default struct constructor sets the struct memory to 0, effectively setting all variables to their default values.
In case of ints, it will be 0. For reference types, it will result in null.
(in other words, for any type T it will be default(T)).
Note that when you write a custom constructor in a struct, you must initialize all member fields.
When you write
int x;
this is similar to
Point p1 = new Point(); (considering Point structure is already defined)
in both the cases all integer variables will have default value of 0 and not null, which is is basically what is used in C# to denote 'nothing' and can be assigned only to reference types.
As well, in c# everything is a class, so when you write
int x = 10;
you are creating an instance of class Int32, though the run time will handle this as value type instead of ref type, as special case.
Same is true for other basic types like, Long, DateTime and few others
classes deal with the reference types and traditional data types deal with the value type just for example :
int i=5;
int j=i;
i=3 ; //then this will output i=3 and j=5 because they are in the different memory blocks .
Similarly if we talk about the object of a class say point class
class point
{
public int x,y;
void somefucnt(point p,int x)
{
Console.writeline("value of x is "+p.x);
x=22;
Console.writeline("value of x is "+p.x);
}
}
class someotherclass
{
static void Main(string [] args )
{
p1.x=10;
p1.somefunct(p1,p1.x);
}
}
Both console.write statements are printing 10 , despite ive changed x to some other value ? why is it so ?since p is just the reference to x so it should be updated by changing values of x . this thing is really confusing me alot .
The observed behavior has nothing to do with Value types vs Reference types - it has to do with the Evaluation of Strategy (or "calling conventions") when invoking a method.
Without ref/out, C# is always Call by Value1, which means re-assignments to parameters do not affect the caller bindings. As such, the re-assignment to the x parameter is independent of the argument value (or source of such value) - it doesn't matter if it's a Value type or a Reference type.
See Reference type still needs pass by ref? (on why caller does not see parameter re-assignment):
Everything is passed by value in C#. However, when you pass a reference type, the reference itself is being passed by value, i.e., a copy of the original reference is passed. So, you can change the state of object that the reference copy points to, but if you assign a new value to the reference [parameter] you are only changing what the [local variable] copy points to, not the original reference [in the argument expression].
And Passing reference type in C# (on why ref is not needed to mutate Reference types)
I.e. the address of the object is passed by value, but the address to the object and the object is the same. So when you call your method, the VM copies the reference; you're just changing a copy.
1 For references types, the phrasing "Call By Value [of the Reference]" or "Call by [Reference] Value" may help clear up the issue. Eric Lippert has written a popular article The Truth about Value Types which encourages treating reference values as a distinct concept from References (or instances of Reference types).
void somefucnt(point p,int x){
Console.writeline("value of x is "+p.x);
x=22;
Console.writeline("value of x is "+p.x);
}
Here, the x=22 won´t change p.x but the parameter x of (point p,int x)
Normally, your assumtion about values/references is ok (if I understood it correctly).
Tip: Google for c# this instead of passing a object to it´s own method
You change the value of the parameter (x), not the value of p.x, value types are passed by value unless you use the ref keyword.
Like in your first example, there is no relationship between i and j as well as the parameter x, and p1.x.Each variable has it's own space in the memory.So changing one of them doesn't affect to the other.
You have two different variables named x in the somefucnt function. One is the member variable x which you are trying to change, the other is the function input parameter in void somefucnt(point p, int x). When you say x = 22, the input parameter x is changed instead of the member variable x.
If you change the line x = 22 to this.x = 22 then it should work as you expect.
Side note:
A good practice to avoid confusion is to always have class members private and name them as _x. Otherwise, have public auto properties in CamelCase, like this:
public int X { get; set; }
These methods avoid ambiguity between class variables and function input variables.
Basic manuals on C# state that to change a value type when passed to another method you must use the out or ref keywords, etc.
For example:
int Loop(int counter)
{
return(++counter);
}
void ClickIt ()
{
int count = 0;
for (int c1 = 0; c1 < 10; c1++)
{
count = Loop(count);
Console.Writeline(count);
}
}
Here, ClickIt outputs the following result: 1, 2, 3, 4, ... 10
In the example, count (a value type), which is being passed from the method ClickIt to the method Loop without out or ref, is being changed in Loop. And Loop then returns count to the calling method ClickIt which picks up the change to count.
So, my question is: When is a value type, when passed as an argument to another method, required to use out or ref so that the value can be changed?
You have an incorrect understanding of the meaning of "ref", and you are also mixing up values and variables. These are common mistakes.
Let's go back to basics.
A variable is a storage location which can contain a value.
Let's simplify your program:
int M(int x)
{
x++;
return x;
}
void N()
{
int y = 0;
y = M(y);
}
If N is called, what happens?
Imagine a variable is a drawer that can contain a sheet of paper. We make a drawer and label it y. In y we put a piece of paper that says "0". Now we call M(y). What happens?
We make a new drawer labeled "x" and we make a photocopy of the piece of paper in "y". We put the copy in drawer x. y contains a piece of paper that says 0, and x contains a different piece of paper that also contains 0.
Now in M we increment x. What happens? We make a new piece of paper that says 1, throw away the old one, and put the new one in drawer x.
Now we make a photocopy of the value in x, so we have another piece of paper that says 1. When M returns we put that piece of paper into y and throw away the 0 that is already in there.
Did M modify y? No. M only modified x. N modified y, twice. Once when y was created, and once after M returned.
Notice that we made two copies. First, we made a copy of y on the way in to M and copied it to x, and then we made a copy of x on the way out and copied it to y.
Now suppose we have
void P(ref int b)
{
b++;
}
void Q()
{
int c = 0;
P(ref c);
}
We run Q. What happens? We make a drawer called c and put a piece of paper in it that says "0". What happens when we call P? Something different. This time we make a drawer called b and put a piece of paper in it that says "don't use this drawer! Every time you try to use this drawer, use c instead!" That is, b refers its behaviour to c.
Now P tries to increment b. It tries to get a value out of b, but discovers that b says no, use c. So it looks in c, finds 0, makes a new piece of paper that says 1, replaces the contents of b -- no, wait, we need to replace the contents of c -- with 1, and returns. So c is updated to 1.
Does it make sense why these two things are different? The first is called copy in, copy out because we make a photocopy of y on the way in to M, and a copy of x on the way out. The second is called by reference because b refers its behaviour to c; no values are copied.
In your sample you actually do not modify passed count variable.
When it's passed, a copy inside a Loop function scope is being created. Then modification done, you return in back and set to your count variable.
Actually, the purpose of:
ref - is that variable should be already initialized before passing into function. And copy is not created inside. You modify passed variable directly. As result - you don't need to return modified value and set it back to your variable.
out - it does not require passed variable to be initialized before passing into your function. But it actually MUST be initialized inside that function.
Hope that's all.
Long comment...
Your code could be confusing - make sure to separate result of function from parameter:
void ClickIt ()
{
int count =0;
for (int c1 =0; c1 < 10; c1++)
{
var resultCount = Loop(count);
Console.Writeline("Result:{0}, count:{1}", resultCount, count);
}
}
Answer (opinion based) - you should almost never use out/ref - it is much harder to reason about than return values. Such functions also are hard to use in LINQ/lambda expression due to need of arguments to be variables.
Common case when it somewhat acceptable is when function returns more than one result (like TryParse), but consider if some other return type (i.e. nullable int?) would work too.
can anyone suggest me the exact use of out keyword as a paramter, and how its connected for returning multiple values from the function, as in this POST, i am confused with out variable with normal variable. can anyone help me for this.
This is frequently confusing, and I think the MSDN documentation actually is a bit "clear only if already known". That is, it is correct, but it really only makes sense if you already understand the concept.
Here's how I think of it.
A regular parameter makes a copy of the value of the argument. When you say:
static int M(int z) { z = z + 1; return z; }
...
int x = 123;
int y = M(x);
That is just like you said:
int x = 123;
int z = x; // make a copy of x
z = z + 1;
int y = z;
A ref or out parameter make an alias for an existing variable. When you say
static void N(ref int q) { q = q + 1; }
...
int x = 123;
N(x);
That is the same as saying:
int x = 123;
// MAGIC: q is now an another name for variable x
q = q + 1;
q and x are two different names that refer to the same variable. Incrementing q also increments x because they are the same. z and x in the previous example are two different names that refer to two different variables. Incrementing z does not change x.
Summing up: "out" and "ref" just mean "do not make a new variable; rather, temporarily make a second name for an existing variable".
Is that now clear?
UPDATE: I did not say what the difference between "out" and "ref" is. The difference is simple. On the "caller" side, a "ref" must be a definitely assigned variable before the method is called. An "out" need not be. On the "callee" side, a "ref" may be read before it is written to, but an "out" must be written to before it is read. Also, an "out" must be written to before control leaves the method normally.
MSDN documentation already does a great job explaining this:
The out keyword causes arguments to be passed by reference. This is
similar to the ref keyword, except that ref requires that the variable
be initialized before being passed. To use an out parameter, both the
method definition and the calling method must explicitly use the out
keyword. For example:
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
It's very frequently used in a pattern that "tries" to get a value, something like:
int result;
if(Int32.TryParse("123", out result))
{
Console.WriteLine(result + 1);
}
out keyword should be used when you want to:
a) Allow your function to modify specific variable from calling code stack AND
b) enforce setting this variable value inside your function
MSDN is always a good place to start
In most languages c# included you can pass values in 2 ways, by value, by reference.
by value gives the method a copy of your data, so changing the data wont have any effect on the original data
by reference essentially gives the method the memory address of your data, so if the method modifies the data, it changes the original.
Out is a special type of ref, in that you do not need to initialise the variable before you call the method, it can be called with null being passed in. and it MUST be set by the method.
Another way you can think of it (from the outside code's point of view) is:
val = read only
ref = read/write
out = write only.
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
out keyword is good if you want to return multiple values of pre-defined types (for example an int, a List<string> and a DateTime), and you don't want to create a new class just for this purpose.
Ok,
let look at the usual pattern for this kind of function - the TrySomething.
Suppose you have a function that might succeed giving you an value or not but you don't won't to use an exception for this because you don't want the overhead or it's a common trait.
Then you normaly return true if the method suceeded and false if not. But where would you put your outputvalue to?
One possible answer is using an out parameter like this:
bool TrySomething(MyInputType input, out MyOutputType output)
{
output = default(MyOutputType);
/* ... Try getting the answer ... */
if (!successful)
return false;
output = successfulOutput;
return true;
}
Remark:
Or you might consider using a Tuple<bool,MyOutputType> and indeed F# interpretes the pattern above as resulting in such a tuple by itself.