0

Just want to get some advice on what is the best practice to share a struct.

I have a number of internal classes that I would like to use the same instance of a struct. Instead of passing struct as a param is there an alternative?

Thanks in advance.

11
  • 4
    Structs don't have instances. You probably shouldn't be using a struct.
    – SLaks
    Oct 12, 2011 at 2:13
  • ok then a class it is. thanks ;)
    – nixgadget
    Oct 12, 2011 at 2:15
  • Parameter passing of some form is necessary to avoid globals (and globals should typically be avoided).
    – Corbin
    Oct 12, 2011 at 2:18
  • Good, now make that class a singleton, and everything will be able to access the same instance without passing it around as a parameter.
    – slugster
    Oct 12, 2011 at 2:19
  • A singleton is a glorified global. Singletons should typically be avoided unless there is a situation in which you really do only want one of something (and even then, it's typically better to still pass it around).
    – Corbin
    Oct 12, 2011 at 2:20

2 Answers 2

2

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.

1

You should consider using structs only for defining data structures that looks like basic types like strings, int etc..

Those structs are treated as value types in opposition of classes that are treated as reference types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.