Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an example of "this" assignment in C#?

Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.

like image 800
Alexander Prokofyev Avatar asked Sep 16 '08 06:09

Alexander Prokofyev


People also ask

What is an assignment statement in C?

C provides an assignment operator for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.

Is == an assignment operator?

The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.


1 Answers

The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type:

public struct MyValueType
{
    public int Id;
    public void Swap(ref MyValueType other)
    {
        MyValueType temp = this;
        this = other;
        other = temp;
    }
}

At any point a struct can alter itself by assigning to 'this' like so.

like image 152
ZeroBugBounce Avatar answered Sep 22 '22 05:09

ZeroBugBounce