s-a-n s-a-n - 8 months ago 69
C# Question

Instantiating a class inside a method

Is it possible to do this

void Instantiate(Class c) {
c = new Class();
}

Class c1 = null;
Instantiate(c1);
c1.property .....gives me null reference exception


Can a class be instantiated inside a method and be used outside it?

Answer Source

Yes, but you have to pass the argument by reference:

void Instantiate(ref Class c) {
   c = new Class();
}

Class c1 = null;
Instantiate(ref c1);

All parameters are passed by value by default. In case of reference types the reference is the value being passed. Because of that if you change internal state of the object it will be visible outside of the method (e.g. adding an element to a list). But, but you can't replace the entire instance - that change won't be visible to the caller.

Let's say you have a List<T>:

var myList = new List<T>();

let's assume it's initialized in some memory location 0x1234. Now you pass it to a method which takes List<T>:

void doSomethingWithAList(List<T> list)
{
}

And later

doSomethingWithAList(myList);

At this point both myList outside of the method and list inside doSomethingWithAList point at the same addres (0x1234). If you do list.Add(default(T)) and later callmyList.Lenghth you'll get back 1, because they are both pointing at the same object at 0x1234.

However, if inside doSomethingWithAList you assign a new list to list:

void doSomethingWithAList(List<T> list)
{
    list = new List<T>();
}

only list points at that new object. myList still points at 0x1234.

Once you make the method take List<T> by reference updating what list points too will also update what myList points to outside of the method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download