JakkeFire
JakkeFire

Reputation: 99

Hide derived class

i'm new to C# or OOP in general and was wondering if next is possible with inheritance:

i want to setup a communication link and want to be able to use udp or serial communication. So i define an abstract base class 'Link' with methods .open, .close, .send, .receive From this base class i derive 2 classes 'LinkUdp' and 'LinkSerial' and override the 4 methods

Now is it possible to directly write code with an object to the 'Link' class ? I mean like:

Link myLink = new Link("10.0.0.1"); //now the compiler knows to use LinkUdp class
Link myLink = new Link("COM1"); //compiler knows to use LinkSerial class

or do i have to write my code dedicated like:

LinkUdp myLink = new LinkUdp("10.0.0.1");

Hope this is clear enough... Thanks

edit: i would like to use the 'Link' class so i can pass the object on to a subclass without having to write 2 different implementations: so after this i have a class

CommunicationHandler myComm = new CommunicationHandler(myLink);

and then this handler doesn't have to worry about me using udp or serial...

Upvotes: 1

Views: 97

Answers (2)

Tim Rutter
Tim Rutter

Reputation: 4679

No a constructor for a class can only return that class' type. You could alternatively have a static Create function (factory pattern):

Link myLink = Link.Create("10.0.0.1");

eg

public static Link Create(string something)
{
    if (//determine that "something" is an IP address))
        return new LinkUdp(something);
    else
        return new LinkSerial(something);

}

Upvotes: 7

Patrick Hofman
Patrick Hofman

Reputation: 156928

There is no way to let the compiler choose which type to instantiate based on just a variable name (unless you use reflection or a factory to create the right instance for you).

This is possible though and it shows one of the benefits of inheritance:

Link myLink;
myLink = new LinkUdp("10.0.0.1");
myLink = new LinkSerial("10.0.0.1");

No matter what follows, myLink can be either of them. The type used is Link, which allows your application to be as generic as possible.

Upvotes: 1

Related Questions