Question

I know that a Struct is a value type and a Class is reference type, however I cannot seem to get around this issue.

I have a class that has a list of a struct:

public class Basket
{
  string ID{get; set;}
  List<Fruit> fruits{get;set;}

  public struct Fruit
  {
      string Name{get;set;}
      bool IsFresh;
  }
}

when passing a class instance to another class I want to update one of the Structs' IsFresh property but the code just skips it:

public class Customer
{
    public string Name{get;set;}
    public Basket Basket{get;set;}

    public Customer(string name, Basket basket)
    {
         this.Name = name;
         this.Basket = basket;
    }

    public ChangeBasket()
    {
        //CODE THAT IS NOT WORKING
        Basket.Fruits[0].IsFresh = false;
    }
}

The same referenced class is being modified and the valued structs should be updated.

why is that not working?

Was it helpful?

Solution

You should not generally write mutable structs. Instead, assign a whole new struct. See here. Basically what's happening is that you're modifying a copy of your struct, as it is a value type.

OTHER TIPS

First of all, you have some problems with access modifiers(use public when you want to access your code outside your class\structs).

Your problem is due to the reason that structs are value types, so when you access a list element you will access a copy of the element which has been returned by the indexer's "getter" of the list and not the list itself. That means if you try to update the instance, the update will not really influence a change on the "real" entity, but on the copied one and that's why you get a compilation error.

This basket.Fruits[0].IsFresh = false;

should be:

Basket.fruits[0].IsFresh = false;

Does that fix it?

It seems you can't use the indexer when the list is a list of structs. the following code works:

var x = Basket.Fruits[0];

x.IsFresh = false;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top