c# - Indexer that points to item in struct array don't work -


i have class called surface, in class have array of type struct color.

public class surface {     private color[,] pixels;      public color this[int x, int y]     {         { return pixels[y, x]; }     } }  [structlayout(layoutkind.explicit)] public struct color {     [fieldoffset(0)]     public byte r;      public void set(byte r)     {         r = r;     } } 

however when try access color using indexer don't updated.

mysurface[x, y].set(255); // not work, don't error color don't updated. 

how can solve problem?

how can solve problem?

well avoid creating mutable structs , exposing public fields, start with. that's problem coming from. code effectively:

color tmp = mysurface[x, y]; // take copy array... tmp.set(255); // affects copy 

to change array, you'll need call setter on indexer instead. example:

color tmp = mysurface[x, y]; tmp.set(255); mysurface[x, y] = tmp; 

assuming have several values in struct, simpler if you'd make struct immutable provide methods returned new values, datetime.adddays etc. write code like:

mysurface[x, y] = mysurface[x, y].withred(255); 

options if want avoid using setter:

  • use ref return c# 7: redefine indexer return ref color; although can't have setter.
  • make color class instead of struct
  • use reference type inside color, don't need change bits in color value itself. (this nasty - i'm not suggesting that.)

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -