user34537
user34537

Reputation:

Use Struct as a Ptr/class? Need a fix .NET

I wrote a bunch of code and i would like to fix it the fastest way possible. I'll describe my problem in a easier way.

I have apples and oranges, they are both Point and in the list apples, oranges. I create a PictureBox and draw the apple/oranges on screen and move them around and update the Point via Tag.

The problem now is since its a struct the tag is a copy so the original elements in the list are not update. So, how do i update them? I consider using Point? But those seem to be readonly. So the only solution i can think of is

I really only thought of this solution typing this question, but my main question is, is there a better way? Is there some List<Ptr<Point>> class i can use so when i update the apples or oranges through the tag the element in the list will update as a class would?

Upvotes: 0

Views: 66

Answers (3)

Adam Robinson
Adam Robinson

Reputation: 185703

Using your naming:

public class Ptr<T> where T : struct
{
    public T Value { get; set; }

    public Ptr(T value) { Value = value; }
}

You can then make your list a List<Ptr<Point>>.

Edit

Alternatively, the absolute easiest solution would be to recreate the Point structure as a class within your own namespace.

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

That's obviously the barebones implementation; if you need additional functionality you'll obviously need to implement that yourself. This will, however, give you a mutable Point class.

Upvotes: 1

SLaks
SLaks

Reputation: 888273

You should make a class to contain your Points.

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72678

If value semantics are not what you want, then you should be using class instead of struct. Is there any reason why you cannot convert your structs to classes?

Edit Ignore the above, I didn't quite understand what was being asked, but I think SLaks has the correct solution.

Upvotes: 0

Related Questions