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?

3
  • 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. Commented Feb 25, 2021 at 15:52
  • 2
    Thanks for feedback. I've changed my code to be more readable. Commented Feb 25, 2021 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. Commented Feb 25, 2021 at 16:01

1 Answer 1

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
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@PiotrZdun: exactly. Since the set() "method" does not have a parameter for the new value, value does the magic.
Thank you. I am learning from Data Structures and Algorithms Using C# and I thing C# changed a little bit. Thanks for help.
I highly recommend the C# in a Nutshell to better understand the language. Keep learning friend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.