Izzy
Izzy

Reputation: 1816

Preserving object reference after "new"

I'm trying to, in essence, cheaply reference a base object so that it can be built fully later on and be easily referenceable by anything not directly involved within the building process of that object. However, when I have an object that makes sense to construct during the build process (its actually a factory that creates other objects that use a that are reliant on "a" and it makes sense to build these objects within the switch case.)

I've considered using pointers but I don't think they'll be appropriate.

using System;

namespace ConsoleApplication5
{
    class ClassA
    {
        public virtual void hello()
        {
            Console.WriteLine("Hello World!");
        }
    }

    class ClassB : ClassA
    {
        public override void hello()
        {
            Console.WriteLine("Goodbye World!");
        } 
    }

    class ClassC
    {
        ClassA m_object;

        public ClassC(ClassA a)
        {
            m_object = a;
        }
        public void run()
        {
            m_object.hello();
            Console.WriteLine(m_object.GetType().ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassA a;

            ClassC c = new ClassC(a);

            //switch(something)
            //{
                //case "somethingElse":
                    a = new ClassB();
                    c.run();
                    //...
                //break;
            //...
            //}
            //CompleteAGenericCollationTaskWith(a);
        }
    }
}

Basically:

I'm trying to: Pass a shared reference of an object before it's created, to an object, so that I can have (preferably) read-only access from it from inside that second object.

I suspect it has something to do with a = new ClassB(); overwriting the reference but I'm only about 60% sure it's the case and have no idea how to preserve it without using pointers.

Question:

How do I make this work? Do I need to change my structure(likely)? Can I do this while maintaining ClassA and ClassB with minimal changes to ClassC and Program?

Upvotes: 0

Views: 103

Answers (1)

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

You need to read the page on references in MSDN, it explains how to do this very verbosely: http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

Having said that, while the 'ref' keyword will solve this specific problem without modifying too much code, it reeks of bad coding style to reference a not-yet-instantiated object. You should probably refactor the code to correctly respect instantiation order, for example by passing the instance of ClassB to the 'run' method of c.

Upvotes: 1

Related Questions