1

I have code as follow:

struct Name
{

private int age;

public int Age
{
  get
  {
    return age;
  }
  set
  {
    age = Age;
  }
}
public Name(int a)
{
  age = a;
}

};

  class Program
  {
    static void Main(string[] args)
    {
      Name myName = new Name(27);
      Console.WriteLine(myName.Age);
      myName.Age = 30;
      Console.WriteLine(myName.Age);
    }
  }

As you can see I am trying to change value of Age using my property. But i am getting still the same value which I pass when I am creating a object of struct Name. I know that struct are immutable in C#, but i thought i would bee able to change field in them. I am very confused. Could someone explain me what is going on?

  • 2
    Thanks for the example. It seems reproducible. However, it could possibly be more minimal by just demonstrating what the problem is. Maybe you want to create a copy of your project and then remove all code which is not relevant. E.g. I see no real value in providing FirstName, MiddleName and LastName if all implementations work the same way. – Thomas Weller Feb 25 '21 at 15:52
  • 2
    Thanks for feedback. I've changed my code to be more readable. –  Feb 25 '21 at 16:00
  • 2
    You can have a mutable or immutable struct in C#, it's up entirely on how do you code in it. But generally it's agreed upon that [mutable structs are evil](https://stackoverflow.com/q/441309/2557263). – Alejandro Feb 25 '21 at 16:01

1 Answers1

3

Structs in C# are not immutable by default. To mark a struct immutable, you should use the readonly modifier on the struct. The reason your properties aren't updating is that your syntax is wrong. You should use the value keyword to dereference the value provided to the setter.

public int Age
{
  get
  {
    return age;
  }
  set
  {
    age = value;          // <-- here
  }
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Timothy Stepanski
  • 1,186
  • 7
  • 21
  • 2
    @PiotrZdun: exactly. Since the `set()` "method" does not have a parameter for the new value, `value` does the magic. – Thomas Weller Feb 25 '21 at 16:00
  • Thank you. I am learning from Data Structures and Algorithms Using C# and I thing C# changed a little bit. Thanks for help. –  Feb 25 '21 at 16:03
  • 1
    I highly recommend the [C# in a Nutshell](http://www.albahari.com/nutshell/) to better understand the language. Keep learning friend. – Timothy Stepanski Feb 25 '21 at 16:04