-2

In C# I want to pass a reference to an object that is not yet instantiated. Like this:

    MyClass obj = new MyClass(obj);

In C++ I could do it like this:

    class MyClass {
    public:
        MyClass( MyClass **obj ) : the_obj( obj ) { }
        MyClass** the_obj;
    };
    MyClass *obj = new MyClass(&obj);

How do I do that in C#?

Regards.

Generic Name
  • 1,083
  • 1
  • 12
  • 19
  • 1
    Do you want an object that references itself? – Arturo Torres Sánchez Oct 23 '14 at 21:05
  • Why do you want to do this? By the way, C# has pointers. See [Is there pointer in C# like C++? Is it safe?](http://stackoverflow.com/questions/2333574) – mason Oct 23 '14 at 21:05
  • 3
    Pointers should be used as a last resort, in my opinion. – Arturo Torres Sánchez Oct 23 '14 at 21:06
  • 4
    It would really help if you explained [what you are trying to accomplish](http://meta.stackexchange.com/questions/66377/), not what mechanism you have decided to use. – Dour High Arch Oct 23 '14 at 21:10
  • 1
    When you get into problems with the language such as this, it is generally a sign that it is not the right approach (at least for the language you are using). There may be an alternative solution to what you are trying to achieve. If you could provide details as to what your end goal is, we could perhaps assist with some alternatives – Srini Oct 23 '14 at 21:13
  • Is this about using uninitialized references, or about references of references resp. pointers of pointers? – Peter - Reinstate Monica Oct 23 '14 at 21:37
  • Yes. I want sn object that references itself. – Generic Name Oct 25 '14 at 22:38

1 Answers1

0

Just create a mutable class that has a reference to the type you are interested in as a member:

public class Wrapper<T>
{
    public T Value { get; set; }
}

Wrapper<MyClass> wrapper = new Wrapper<MyClass>();

You now have a reference to an instance with a reference to an instance of MyClass.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • @PeterSchneider It's named `wrapper`. It is a reference to an uninitialized reference to a `MyClass`. – Servy Oct 23 '14 at 21:10
  • @PeterSchneider Yes, it does, and that object is itself a reference, because it's a reference type. This is the moral equivalent of a pointer in C/C++. – Servy Oct 23 '14 at 21:11
  • The field underlying Wrapper's automatic property `Value` is null, isn't it? – Peter - Reinstate Monica Oct 23 '14 at 21:13
  • 1
    @PeterSchneider At first, yes. It can be assigned an instance. The fact that it's null is what makes it a pointer to an uninitialized pointer, which is what was specifically asked for. – Servy Oct 23 '14 at 21:18