Hi again,
I have a simple question. What's best practise about instantiation? Put it inside a method or outside (if possible)?
Thanks
using System;
class Test
{
public string name;
static void Main(string[] args)
{
Test2 myObj = new Test2(); // this must be here otherwise: object reference is required for a non-static field
myObj.myMethod();
}
}
class Test2
{
Test myObj = new Test(); // this can be here or in the method myMethod
public void myMethod()
{
myObj.name = "Bob";
Console.WriteLine(myObj.name);
}
}
Aravind GovindarajPosted Jan 1, 2023, 2:33 PM
Kindly walkthrough dependency Injection , u will get some idea and advantage about passing object from one to another level with coupled approach.
Valerie MeunierPosted Jan 3, 2023, 1:16 PM
OK, but can you fix the error of your own code, please?
Valerie MeunierPosted Jan 1, 2023, 3:05 PM
Thanks
Sachin SinghPosted Jan 1, 2023, 2:49 PM
The best is always inside a constructor.
But, yes there are difference between instanciation at class level vs at method level. I can write all the differences but there is already a good answer in stackoverflow.
https://stackoverflow.com/questions/15224734/difference-between-class-level-instantiation-vs-method-instantiation