-3

I'm new to C#. I searched the web with no success on finding an answer to my question, maybe it's only a term/syntax which I'm missing out.

I'm learning some program which somebody else wrote. The program includes some classes in different files which are included with the project.

at the main program file instead of the way I know for declaring a new instance of these classes this method is used:

 namespace Technology_A3000_A4_A42107
{
    public partial class FormTechnology : Form
    {
        ...
        private AST_NET _device;
        private ClassTechnology _technology;
        private ClassGain _gain;
        ....
    }


           public FormTechnology()
        {
            ...
            _device = new AST_NET();
            _technology = new ClassTechnology(_device);
            _gain = new ClassGain();
            ....
        }

    ....    

What exactly is done here? is this equivalent to writing the row below, or is it needed due to some external file or some other property of the classes?

private AST_NET _device = new AST_NET(); 

Thanks in advance and sorry if this is not an appropriate question. Amitai

Amitai Weil
  • 57
  • 2
  • 10
  • Possible duplicate of [C# member variable initialization; best practice?](https://stackoverflow.com/questions/298183/c-sharp-member-variable-initialization-best-practice) – UnholySheep Sep 27 '17 at 08:29

2 Answers2

0

  public FormTechnology()
        {
            ...
            _device = new AST_NET();
            _technology = new ClassTechnology(_device);
            _gain = new ClassGain();
            ....
        }
        
    

This FormTechnology is the constructor of the class FormTechnology. When you creating an instance of the FormTechnology it will call the constructor. As a result of that it will create the instance of the below classes

            _device = new AST_NET();
            _technology = new ClassTechnology(_device);
            _gain = new ClassGain();
user3808887
  • 319
  • 2
  • 9
0

The c# compiler (like Java) creates an output like

new Form().ctor()

Where ctor() is the constructor you are defining like this

public Form(){
    // Some code
}

Basically the custructor is a function called right after creating a new instance of a class. You cannot prevent this. So I think (not exactly sure) but the class based initialization is done before the constructor. So values like this

public int value = 10;

are assigned before the constructor. Correct me if I am wrong.

However that is a bad design because u cannot have conditions.

  • In a constructor you can dynamically set values.
  • In the field initialization (shown above) the values must be known at compile-time.

Hope this helps?

Meikel
  • 314
  • 2
  • 12