I think you are asking on how to create a reference or a pointer to a struct. In C# you can do this only with structs made up of only intrinsic value types (int
, byte
, float
, double
, char
)
Take the following example and compile it with unsafe option
public struct Data
{
public int id;
public double x;
}
unsafe class A
{
Data* data;
public A(Data* data)
{
this.data = data;
}
public int ID { get { return data->id; } set { data->id = value; } }
}
unsafe class B
{
Data* data;
public B(Data* data)
{
this.data = data;
}
public double X { get { return data->x; } set { data->x = value; } }
}
unsafe class Program
{
static void Main(string[] args)
{
Data store = new Data();
A a = new A(&store);
B b = new B(&store);
a.ID = 100;
b.X = 3.33;
Console.WriteLine("id={0} x={1}", store.id, store.x);
}
}
It will print out "id=100 x=3.33"
even though the value type variable store
is never directly assigned those values. Both classes contain a reference to the struct
and can manipulate its values.
Want to learn more about pointers to structs, look at this article, or this MSDN document. Yes, the above is legit C# code and despite the unsafe keyword is rather reliable and robust when properly coded. Oh, and it is wicked fast too.