user12330683
user12330683

Reputation:

Immutable structure in c#

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?

Upvotes: 1

Views: 236

Answers (1)

Timothy Stepanski
Timothy Stepanski

Reputation: 1196

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
  }
}

Upvotes: 3

Related Questions