Trevor McKenzie
Why is a Variable declared as a private class member, able to change its value without invoking its object.property ?

A question was asked about “the difference between Variable and Property”. In response to Mr. Patel’s answer. I pose a follow up question. “ Why am I allowed to make a change to the variable’s value, without invoking the property, when the Varible is still declared as Private?. The modified problem is listed below.

using System;
namespace Advanced_
{
class TestClass
{
private string x = “Test Test”;
void TestFun()
{
Console.WriteLine(x);
}

  1. public string ChangeName
  2. {
  3. get { return x; }
  4. set { x = value; }
  5. }
  6. // Application Execution begins Here!
  7. static void Main(string[] args)
  8. {
  9. // Class instantiation / Objection creation begins
  10. TestClass obj = new TestClass();
  11. // First Method Call/ Invocation to Object 'TestFun' with original string value
  12. obj.TestFun();
  13. // Second Method Call/ Invocation to Object 'TestFun' with modified string value
  14. // Note Property is not called.
  15. obj.x = "Test Failure";
  16. obj.TestFun();
  17. //obj.ChangeName = "Property Testing ";
  18. }
By Trevor McKenzie in .NET on Sep 29 2022


Most Popular Job Functions


MOST LIKED QUESTIONS