Reading C# In Depth, 2nd edition, section 2.1.2 on combining and removing delegates.
The subsection title states that "delegates are immutable" and that "nothing about them can be changed." In the next paragraph, though, it talks about using constructs like
x += y;
where x and y are variables of compatible delegate types.
Didn't I just change x? Or does the immutability part deal with when x is disposed of when I do this (i.e., immediately)?
That's like doing:
string x = "x";
string y = "y";
x += y;
Strings are immutable too. The code above not changing the string objects - it's setting x to a different value.
You need to differentiate between variables and objects. If a type is immutable, that means that you can't change the data within an instance of that type after it's been constructed. You can give a variable of that type a different value though.
If you understand how that works with strings, exactly the same thing is true with delegates. The += actually called Delegate.Combine, so this:
x += y;
is equivalent to:
x = Delegate.Combine(x, y);
It doesn't change anything about the delegate object that x previously referred to - it just creates a new delegate object and assigns x a value which refers to that new delegate.
You have changed x, but didn't change its value (i.e. the delegate it was holding).
It's the same as:
int num = 4;
num += 2;
Related
Assume there is the following delegate:
delegate int Foo(int x);
I've seen people create this delegate in multiple ways, for example:
Example 1:
Foo f = Bar;
With Bar being:
int Bar(int x) => x * 2;
Example 2:
Foo f = new Foo(x => x * 2);
Example 3:
Foo f = x => x * 2;
Are there any differences (pro's, con's, efficiency, etc.) other than personal coding style preference?
Although examples 2 and 3 are pretty much identical, the two may become different from example 1 when used as local declarations.
There is no difference between 2 and 3: in 2, you specify delegate type explicitly, while in the second case you let the compiler figure out the type of the delegate by looking at the type of f. When f is a local variable, you can further simplify the declaration to
var f = new Foo(x => x * 2);
so that Foo is specified only once.
The first example uses a lambda-bodied method to define a delegate through a method group. The obvious difference here is that this way of declaring a delegate requires a separate method.
However, there is another subtle difference here: when delegates from examples 2 and 3 are used in a local context, they can close over local variables. In contrast, example 1 cannot capture local variables, even if you use it in a local context.
Code examples 2 and 3 let you do this:
Foo Make(int y) {
var res = x => x * y; // y is captured from the context
return res;
}
while example 1 is limited to using x that you pass and any fields of the object that declares Bar.
Therefore, you need to consider these points when deciding among these three options:
If you need a delegate that does not close over local variables, and relies on logic that can be used elsewhere, use method group,
If you need a delegate that closes over local variables, use 2 with var, or 3,
If you are declaring a field, use 3, because you must specify the type of the field anyway.
The main difference is that in Example 1 you can reuse your function Bar. I believe that 2 and 3 are synonymous and that the lambda expression is just syntactic sugar for the anonymous function.
The first, example below is called expression bodied method, so the delegate will refer to this method which returns an int and will take whatever value of x is and multiply it by 2.
int Bar(int x) => x * 2;
The second, example below is using a lambda expression, it is instantiating the delegate and passing a reference to the method that will return the value of x multiplied by 2.
Foo f = new Foo(x => x * 2);
The last example is just syntactic sugar which behind the scenes is pretty much the same as the example above.
Foo f = x => x * 2;
Are there any differences (pro's, con's, efficiency, etc.) other than
personal coding style preference?
they all essentially accomplish the same end result, however, the first example you could reuse the method as many times as you want whereas the last two you're passing in a behaviour that just gets executed (at a later time) without any identifier to the method for later reuse.
I am having problems with this bit of code
I have this structure
public struct bounds
{
public int xmax = 0;
public int xmin = 0;
public int ymax = 0;
public int ymin = 0;
};
and I make a list out of it
List<bounds> map = new List<bounds>();
I am trying to store the boundaries of a space (or object) in a 2D array (its xmax, xmin, ymin, & ymax) I have this integer y variable which is going to be some number when it gets to this code, but I keep getting red lines under the code associated with my list "map" (i and j are counters for going through the 2D array)
if(!(map.Contains(y))) //if the list doesn't already have this number
{
map.Add(y);
map[y].xmax = i; //and set its xmax, xmin, ymax, ymin
map[y].xmin = i;
map[y].ymax = j;
map[y].ymin = j;
}
if(map[y].xmax < j) // if its already in the list look at the current
map[y].xmax = j; // boundaries and decide if new ones should be set
if(map[y].xmin > j)
map[y].xmin = j;
if (map[y].ymax < j)
map[y].ymax = i;
if(map[y].ymin > j)
map[y].ymin = i;
The reason for this is a struct is a value type.
When you're reading out the struct from the list, you're getting a copy.
As such, this line of code (and all that looks like it):
map[y].xmax = i;
is modifying the copy you got out from the list.
You can counter this by manually retrieving the copy, modifying it, and placing it back into the list.
Note: Mutable structs generates all sorts of problems. The problem you're having is just one of them, but you should not make them mutable.
Also note: You're using the struct value itself as an indexer into the list, I assume this is an error, and that you're actually using an index variable, otherwise you're really having problems.
Here's a general tip though. If Visual Studio is drawing red squigglies under your code, you can hover the mouse over it to get a tooltip telling you what is wrong. It may cryptic to you, but the error message can be googled much easier:
To use the List indexer, you need to pass an int. You're passing a bounds struct here
map[y].xmax = i;
y has to be an int representing the index you want to access. I'm guessing y is a bounds struct because you've used
map.Add(y);
and your map is of type List<bounds>.
If the purpose of a data type is to encapsulate a fixed set of related but independent values (such as the coordinates of a point), an exposed-field structure meets that description better than any other data type. Such structures should not have many instance methods other than overrides of ToString(), Equals(), and GetHashCode(); it's generally better for structures to use static utility methods than instance methods. For example, this would be problematical:
public void UpdateRange(Point pt)
{
if (pt.X > xmax) xmax = pt.X;
if (pt.Y > ymax) ymax = pt.Y;
if (pt.X < xmin) xmin = pt.X;
if (pt.Y < ymin) ymin = pt.Y;
}
but this would not:
public void UpdateRange(ref bounds it, Point pt)
{
if (pt.X > it.xmax) it.xmax = pt.X;
if (pt.Y > it.ymax) it.ymax = pt.Y;
if (pt.X < it.xmin) it.xmin = pt.X;
if (pt.Y < it.ymin) it.ymin = pt.Y;
}
Note that when classes expose properties of a structure type, it is not possible to modify such properties directly. One cannot use something like:
bounds.UpdateRange(ref myList[4], newPoint);
nor, if UpdateRange were an instance method, could one use:
myList[4].UpdateRange(newPoint);
In the latter situation, the code would compile, but wouldn't work. Instead, one has to use something like:
var temp = myList[4];
bounds.UpdateRange(ref temp, newPoint);
mylist[4] = temp;
Note that the instance method and the static method with a ref parameter are semantically identical in the cases where both will compile. The difference between them is that the static method with a ref parameter will only compile in cases where the ref parameter is a modifiable variable, but calling the instance method on a property will cause the compiler to copy that property to a temporary variable, call the instance method on that, and discard the result.
I would suggest that your type is almost a perfect example of something that should be a structure. If it were a mutable class type, it would be unclear when code which passed a reference to an instance was really passing the instantaneous values the instance happened to hold at the time of a call, or was passing a reference to a "live" entity. Using an immutable class type or a so-called immutable struct type [note that there isn't really any such thing as an immutable value type] would make methods like UpdateRange slower to write and to run, while offering no particular benefit.
The one essential thing to note about the structure type is that each field (e.g. xmin) has no meaning other than "the last value that something stored in "xmin", or zero if nothing has been stored there yet. If code writes 256 to xmin and -234 to xmax, then xmin will hold 256 and xmax -234. Any code which takes abounds` and does anything with it should be prepared for such values just as it would be if it took those fields as four separate parameters.
I mean
double x=5;
double k=Func(x+3.5,h+1.2);//I send x=8.5
double y=x;//x=5;
I want to change it when I send it.
double x=5;
double k=Func(x+3.5,h+1.2);
double y=x;//x=8.5
Is it possible to do?
Please don't do this. Yes. That's my answer.
It is, however, possible because assignment statements with side-effects by definition can be used as expressions. I have removed the extra code that didn't seem to apply.
void Func (double _x) {
// do nothing
// _x = 8.5 when invoked from below
}
double x = 5;
Func(x = x + 3.5); // or Func(x += 3.5)
// x = 8.5
The above is [almost always] much better written with the assignment -- and thus side-effect -- kept separately from the function call itself: (In most cases, both forms have identical semantics.)
x += 3.5;
Func(x);
Happy coding.
If you do wish to use out/ref, keep in mind that it only makes sense to use variables as the out/ref parameters: the expression x + 3.5 is not a variable -- it cannot be assigned to -- and is thus unsuitable. (I believe VB.NET also allows properties.)
void Add(ref double _y, double s) {
// _y = 5
_y += s;
// _y = 8.5
}
double y = 5;
Add(ref y, 3.5);
// y = 8.5
Maybe something like this:
double x=5;
double k=Func(x+=3.5,h+1.2);
double y=x;//x should be 8.5
This way x evaluates to 8.5 before the function is called.
But, may I ask why the need to do this?
Your problem is that you are passing the x variable by copy not by reference. This is why x is still 5 after your functions finishes. You should change your function h from:
h(int x, int y)
to
h(int * x, int *y)
EDIT :
With pointers you pass the variable x and do all your operations on it. With no pointers, the function creates a copy of the variable x and works on it then destroys it when the functions ends. So the real x is not modified.
Pointers and references work together. You declare the function with pointers and pass the variables with reference
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.
These operands may be simple but the difficulty of finding explanations which are definitive and complete prompted me to ask. What are the character combinations containing an operand followed by an equal sign (such as *=, -=,+=, etc), what do they do and how are they useful (especially pertaining to non-numeric fields)?
Examples as well as definitions would be greatly appreciated.
Thanks
They are usually interpreted broadly as:
x += y === x = x + y
(etc for your choice of operator)
however; some languages allow you to have a bespoke += operator*, or may interpret it differently in some scenarios; for example, in C# events, += and -= mean "subscribe via the add accessor" and "unsubscribe via the remove accessor" respectively.
Typically they are just space savers, but there can be semantic differences in some cases.
*=where I mean: very different to just the + operator and assignment
Pretty much all the answers here state that x += y; is "equivalent" to "x = x + y;".
This is not actually true. They are not exactly equivalent for several reasons.
First, side effects are only performed once. Suppose you have
class C { public string S { get; set; } }
class D
{
private static C c = new C();
static C M()
{
Console.WriteLine("hello!");
return c;
}
}
The first line below prints "hello" once, as you would expect. The second prints it twice.
D.M().S += "abc";
D.M().S = D.M().S + "abc";
Second, the type system works differently for compound assignment than for regular assignment.
short b = 1;
short c = 2;
b += c;
b = b + c;
The third line is legal. The fourth line is not; a short plus a short is an int in C#, so b = b + c is an illegal assigning of an int to a short. In this case the compound assignment is actually equivalent to b = (short)(b + c);
If this subject interests you I encourage you to read sections 7.17.2 and 7.17.3 of the C# specification.
The great advantage is that you can say:
x += y;
Instead of the more verbose:
x = x + y;
Sometimes this is nice when working with strings, as you can use += to append text to an existing string.
x += expression is roughly the same thing as x = x + (expression). In other words, it calculates the right-hand side, then applies the + operator to the left-hand side and the result, and then assigns that result back into the left-hand side.
Personally, I'm not a huge fan of them. The /= operator I find a particular menace, as there are many Pascal-related languages that use that to indicate boolean inequality. Someone familiar with that who gets mixed up and tries to use it in C ends up with compiling code that produces some of the most bizzare bugs imagineable.
However, they do come in quite handy when the left-hand side is kind of large, so repeating it would throw out more noise than enlightenment.
These are compound assignment operators. For numeric fields, they're defined to add (+=), multiply (*=), and subtract (-=) the value on the right- from the variable on the left, and assign the result to the variable on the left.
However, C++ supports "operator overloading". Meaning, for any given object, the programmer can define what happens if you write x += 12 and x happens to be an object of type Foo rather than an int. This is commonly done for string classes, so if s1 = "All this" you can write s1 += " and more" and the result will be "All this and more".
Say you have x = 5. If you want to add 1 to x, you can do it in many ways:
x = x + 1;
x += 1;
x++;
++x;
They're all equivalent, and choosing any of those should leave x with 6.
So basically, if you want to multiply, divide, or subtract from x, just change the + operator to what you want.
Sorry, I didn't see that you mentioned non-numeric fields. In C# and in C++, you can do something called an "operator overload" to give a non-numeric object the ability to utilize these compound operators with a user-defined function and/or comparison.
For instance, strings are generally treated as objects and not as primitive data types, but if you execute String s = "hello"; s += "!";, you'll see that s will contain hello!. That's because the String object has an overloaded operator for += that applies an append with the rvalue ("!"--right of the += operator) to the lvalue ("hello"--left of the += operator).
A related question on C# operator overloading:
Simple way to overload compound assignment operator in C#?
If you want an explanation try reading http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound-assignment_operators like someone already suggested, basically a += b; is equivalent to a = a + b;. It's shorthand to make your code easier to write and read.
Here are some examples:
/* Print all evens from 0 through 20 */
for(i = 0; i <= 20; i += 2){
printf("%d\n", i);
}
/* Slow down at a linear pace */
/* Stop after speed is 0.1 or less */
while(speed > 0.1){
speed /= 1.2;
}
speed = 0;
Those should explain it. It applies to bitwise operations as well as arithmetic, but I can't think of any simple uses off the top of my head and I don't want to confuse you. There's the old temp-less swap trick - a ^= b ^= a ^= b; - which will swap the values of a and b without you having to create a temporary variable, but I'm not sure if you know what the bitwise XOR operation is at this point, so don't read into it yet.
With regard to non-numeric fields: what the operators do is completely arbitrary. In C/++/#, you can override what an operator does, allowing you to write something like:
MyObj += MyOtherObj;
// MyObj is now null
When overloading the operators, you can really do whatever you like.