2

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?

Bergkamp
  • 599
  • 2
  • 6
  • 22

4 Answers4

3

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.

Community
  • 1
  • 1
Jordi Vermeulen
  • 1,168
  • 1
  • 10
  • 17
2

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.

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

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

should be:

Basket.fruits[0].IsFresh = false;

Does that fix it?

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
-1

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;

TamerM
  • 722
  • 7
  • 25
  • I disagree. it doesn't. – Bergkamp Apr 20 '14 at 15:07
  • Actually my solution is not what you want. since its a value type, you'd be updated a whole new object instead of the original. the weird thing is that you're not getting a compile error (according to your original post). try cleaning and rebuilding – TamerM Apr 20 '14 at 15:16