-2

I already checked the link "Why can't I set “this” to a value in C#?" and I know that this is read-only. In other words, it (the content) cannot be assigned to another new object. I am just wondering that the philosophy or the consideration of this constraint in C#. If the reason is about to the safety of memory management, C# employs garbage collector and the usage in the future to an object would be determined.

    public class TestClass
    {
        private int Number;
        public TestClass()
        {
            this.Number = 0;
        }
        public TestClass(TestClass NewTestClass)
        {
            this = NewTestClass;        //  CS1604  Cannot assign to 'this' because it is read-only
        }

    }

As the result, it seems that the members needs to be updated one by one.

public TestClass(TestClass NewTestClass)
{
    this.Number = NewTestClass.Number;  //  Update members one by one.
}

Any comments are welcome.

Note: For clarifying, the C++ part has been removed.

JimmyHu
  • 403
  • 1
  • 8
  • 20
  • 7
    Note that in C++ `*this` is not the same as `this`. You are likely running into the same problem here, but my C# is too weak to be certain. Take it from a guy who totally up a few years of C++ code thinking he knew it all from knowing C and Java, Don't try to use C# the same way you would C++. You will end up with code that will (at the very least) make you cringe when you look at it after really learning how to write C#. – user4581301 Aug 14 '20 at 03:47
  • 1
    [By the way, here's what happens in C++ when you assign to `this`](https://godbolt.org/z/5hdTKW). Turns out this doesn't have to be `const` or anything like that because it is a [prvalue](https://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues). – user4581301 Aug 14 '20 at 03:52
  • 4
    C++ will not prevent you from doing things that are completely ridiculous, stupid, or downright dangerous. It's going to assume you know what you're doing even if that's wildly mistaken. – tadman Aug 14 '20 at 03:53
  • 4
    when you do `*this = whatever` you are invoking a copy. You aren't replacing the pointer, you are replacing the contents that it's pointing to. You can do this in C#, just not so ineloquently. – Andy Aug 14 '20 at 03:56
  • @user4581301 Thank you for explanation. Maybe it's a good idea to focus on C# case. So the C++ part has been removed. – JimmyHu Aug 14 '20 at 05:23

3 Answers3

5

I don't think you are quite familiar with what dereferencing a pointer is.

Let's look at this method:

void TestClass::SetThisTest() {
    *this = TestClass(this->IncreaseNumber().GetNumber());      //  Assign new object to *this
}

You believe you are replacing the this, but you aren't. You are replacing the contents pointed to by this. Huge difference. *this != this.

Try this:

void TestClass::SetThisTest() {
    std::cout << "this' address is " << std::to_address(this) << std::endl;
    *this = TestClass(this->IncreaseNumber().GetNumber()); // shallow copy!
    std::cout << "Now this' address is " << std::to_address(this) << std::endl;
}

The address doesn't change, but, the values this points do does. You are invoking (in this case) default shallow copy.

You can do this in C# very easily, you just aren't allowed to be that direct about it.

Here is the C# equivalent of your C++ class:

public sealed class ThisTest
{
    private int _myNumber;

    public ThisTest() { }

    public ThisTest(int number) { _myNumber = number; }

    public static void ShallowCopy(ThisTest to, ThisTest from)
    {
        to._myNumber = from._myNumber;
    }

    public int GetNumber() => _myNumber;

    public ThisTest IncreaseNumber()
    {
        _myNumber += 1;
        return this;
    }

    public void SetThisTest()
    {
        ShallowCopy(this, new ThisTest(this.IncreaseNumber().GetNumber()));
    }
}
Andy
  • 12,859
  • 5
  • 41
  • 56
  • 1
    @Andy Thank you for providing the answer that teaching me how to replace the values `this` points. – JimmyHu Aug 14 '20 at 04:45
  • @JimmyHu If this answer resolved all of your questions, mark it as accepted so that future askers can see that the question may be useful to them if it comes up in a search. – user4581301 Aug 14 '20 at 22:32
3

Because "this" is a reference to the object you instantiated that is only accessible from the object itself.

Why would "this" need to be anything but self-referential?

var s = new Sample { Title = "My Sample" };
//in this case, I want to see a string representation of "s"
Debug.WriteLine(s.ToString());

//in this case, we might want a copy
var s2 = (Sample)s.MemberwiseClone();

public class Sample
{
    public string Title { get; set; }

    public override string ToString()
    {
         //it wouldn't make sense to reference another object's "Title", would it?
         return this.Title;
    }
}
Colin
  • 4,025
  • 21
  • 40
0

Is a "keyword" in C# used to refer the current instance of the class.

You can't assign a value to keyword, another example is keyword "base" and we can't assign a value. E.g. base = "text".

We can assign a value to an object through another class that contains the first.

public class TestClassParent
{
    private TestClass _testObject;

    public TestClassParent(TestClass testOject)
    {
        this._testObject = testObject;
    }
}
JQ963
  • 21
  • 2