How to create an instance of a value type "by reference"

Consider the code and output:

using Microsoft.Xna.Framework; //Where color is from ^ that static Color color = new Color(0, 0, 0, 0); static void Main(string[] args) { Color otherColor = color; color.B = 100; Console.WriteLine(otherColor.B); Console.WriteLine(color.B); Console.ReadLine(); } //output //0 <-- otherColor //100 <-- color 

However, I would like otherColor to carry the same value by reference, so that the output would become

 //100 //100 

If possible, how can I achieve this?

+4
source share
1 answer

You cannot do what you want, at least not directly.

The type Color is a struct . This is a value type. Each instance of Color is a separate copy of the value. It is not possible to get two instances of Color to refer to the same object, no more so that two instances of int can refer to the same object.

Now you can hack something by including Color in your class. The following has not been tested:

 public class ColorByReference { Color TheColor {get;set;} } static ColorByReference color = new ColorByReference {Color = new Color(0,0,0,0)}; static void Main(string[] args) { ColorByReference otherColor = color; color.TheColor.B = 100; Console.WriteLine(otherColor.TheColor.B); Console.WriteLine(color.TheColor.B); Console.ReadLine(); } 
+10
source

Source: https://habr.com/ru/post/1500643/


All Articles