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 GovindarajRank #430 · 5.8K reputationPosted Jan 1, 2023, 9:33 AM EST
Kindly walkthrough dependency Injection , u will get some idea and advantage about passing object from one to another level with coupled approach.
Sachin SinghRank #66 · 26.2K reputationPosted Jan 1, 2023, 9:49 AM EST
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
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 1, 2023, 10:05 AM EST
Thanks
Valerie MeunierRank #1,527 · 1K reputationPosted Jan 3, 2023, 8:16 AM EST
OK, but can you fix the error of your own code, please?