Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, such that the output would become

//100
//100

If possible, how could I achieve this?

like image 938
Colton Avatar asked Dec 21 '22 00:12

Colton


1 Answers

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

The Color type is a struct. It's a value type. Each instance of Color is a separate copy of the value. It is not possible to get two Color instances to refer to the same object, any more than it is possible for two int instances to refer to the same object.

Now, you might be able to hack something by including the Color within your own 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();
}
like image 87
John Saunders Avatar answered Jan 07 '23 03:01

John Saunders