Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share a method between 2 classes C#

I have simplified what I have into this:

class A : SomeClassICantAccess
{
    IVIClass ivi = new IVIClass();

    public A()
    {
        string address = "1111";
        ivi.Initialize(address);
    }

    public void SendCommand(string cmd)
    {
        ivi.Send(cmd);
    }
}

class B : SomeClassICantAccess
{
    IVIClass ivi = new IVIClass();

    public B()
    {
        string address = "2222";
        ivi.Initialize(address);
    }

    public void SendCommand(string cmd)
    {
        ivi.Send(cmd);
    }
}

class Main()
{
    //I want my main to keep this format
    A a = new A();
    B b = new B();

    a.SendCommand("commands");
    b.SendCommand("commands");
}

As you can see, class A and B have identical SendCommand() method, but since their ivis are initialized with different address, the commands are sent to different instruments.

It seems wrong to have a same method copied-pasted in two different classes. But I really want my Main() to look like how it is right now - so that it will be clear whether the SendCommand() is refered to instrument A or instrument B.

How can I merge them?

like image 476
Liren Yeo Avatar asked Jan 17 '26 20:01

Liren Yeo


1 Answers

If this is your actual scenario, there is no need for two class you can deal with A only:

Class definition for A:

class A()
{
    IVIClass ivi = new IVIClass();
    public A(string address)
    {        
        ivi.Initialize(address);
    }
    public void SendCommand(string cmd)
    {
        ivi.Send(cmd);
    }
}

How To Use:

class Main()
{   
    A a = new A("1111");//initialize  ivi with "1111"
    A b = new A("2222");//initialize  ivi with "2222"
    a.SendCommand("commands");
    b.SendCommand("commands");
}
like image 120
sujith karivelil Avatar answered Jan 20 '26 10:01

sujith karivelil