Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 82.3k

What's best practise about instantiation?

Jan 1 2023 2:10 PM

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);
    }
}
 

 


Answers (4)