Search code examples
c#constructorargumentscnctwincat

c# twincat passing argument to class constructor


I wonder what is the best way.

If I need to pass a class to a class constructor why should I use a variable inside my class.

Example:

using Beckhoff.App.Ads.Core.Plc;

Class test()
{
    private static IBAAdsServer AdsServer;
    private static IBAAdsCncClient _cncClient;

    public test(IBAAdsServer _adsServer)   //constructor
    {
        try
        {
            AdsServer = _adsServer;
            _cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
            _cncClient.Synchronize = true;
        }
        catch (Exception Except)
        { MessageBox.Show("Error ! " + Except.Message); }
    }

Why can't I do:

using Beckhoff.App.Ads.Core.Plc;

Class test()
{
    private static IBAAdsCncClient _cncClient;

    public test(IBAAdsServer _adsServer)   //constructor
    {
        try
        {
            _cncClient = _adsServer.GetAdsClient<IBAAdsCncClient>("CNC");
            _cncClient.Synchronize = true;
        }
        catch (Exception Except)
        { MessageBox.Show("Error ! " + Except.Message); }
    }

I would like to use _adsServer in a lot of class not connected, how can I do that properly?

Thanks for help.


Solution

  • Ok, here is like I do now.

    using Beckhoff.App.Ads.Core.Plc;
    
    Class test()
    {
    private static IBAAdsServer AdsServer;
    private static IBAAdsCncClient _cncClient;
    
    public test(IBAAdsServer _adsServer)                  //constructor
    {
        try
        {
            AdsServer = _adsServer;
            _cncClient = AdsServer.GetAdsClient<IBAAdsCncClient>("CNC");
            _cncClient.Synchronize = true;
            Classtocall newClass = ClasstoCall(_cncClient);//Passing the argument directly
    }
    catch (Exception Except)
        { MessageBox.Show("Error ! " + Except.Message); }
    }