Ryan Caputo
Ryan Caputo

Reputation: 63

Inheritance in C# multiple properties for a single property

How would you inherit from one class and have multiples of a single property from it Example

And here is the actual code (So Far)

class NetWorkInterface
{
    public double Vlan;
    public string Ip;
}

class Port : NetWorkInterface
{
    public double PortNumber;
}
public void test ()
{
    Port newport = new Port();
    newport.PortNumber = 7;
    newport.Vlan = 100
}

I want to be able to add multiple interfaces to one port

Upvotes: 2

Views: 244

Answers (3)

patrick
patrick

Reputation: 16949

You can inherit one class per class (no multiple inheritance in C#), or implement multiple interfaces, or do both

public interface NetWorkInterface1
{
  double Vlan {get; set;} 
}

public interface NetWorkInterface2
{
   string Ip {get; set;}
}

class Port : A /* (inherit class before interface) port inherits A & A inherits B*/, NetWorkInterface1, NetWorkInterface2 /* implements interface 1 & 2*/
{
    public double PortNumber;
    public double Vlan {get; set;} 
    public string Ip {get; set;}
}

public class A : B /* A inherits B */
{
  public string AStuff; 
}   

public  class B
{
  public string BStuff;         
}


public void test ()
{
    Port newport = new Port();
    newport.PortNumber = 7;
    newport.Vlan = 100;
    newport.AStuff = "A"; 
    newport.BStuff = "B"; 
}

Upvotes: 0

Loofer
Loofer

Reputation: 6965

Something along the lines off

    public class Port
    {
        public double PortNumber { get; set; }
        public IEnumerable<NetworkInterface> NetworkInterfaceList { get; set; }
    }

Upvotes: 0

Slappywag
Slappywag

Reputation: 1223

I don't think you should be using inheritance here.

If you want a Port to contain a collection of NetworkInterfaces then a better definition of Port might be:

class Port
{
    public double PortNumber;
    public NetworkInterface[] networkInterfaces;
}

Upvotes: 3

Related Questions