cbrockhoff
cbrockhoff

Reputation: 23

Objects with references to other objects of same class C#

I have a class, I would like to contain a list/vector/whatever of pointers to other objects of the same class. An object of the class would represent a coordinate, and the list would contain references to other coordinates that are connected to this one... if that makes sense.

I'm used to C++, where I would have something like:

class MyClass
{
    private:
        std::vector<const MyClass*> vec;
};

I'm trying to do something like the above in C#, but I can't tell how to do it. Do I have to use the unsafe keyword somehow, so I can use pointers, or is there another smarter way to implement something like this in C#?

Upvotes: 1

Views: 117

Answers (2)

Yoseph
Yoseph

Reputation: 2416

For List

class MyClass
{
    public List<MyClass> Vec { get { return vec; } set { vec = value }
    private List<MyClass> vec;
}

Upvotes: 3

dougajmcdonald
dougajmcdonald

Reputation: 20047

You should just setup the class with a List/Enumerable or whatever of you type, so something like:

public class Cake
{
    // public
    public IEnumerable<Cake> Cakes { get; set; }

    // private
    private IEnumerable<Cake> cakes; 
}

Upvotes: 1

Related Questions