Search code examples
c#language-features

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.


Solution

  • 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.