Calling a variable class name

  • Thread starter Thread starter smeagol
  • Start date Start date
S

smeagol

Look this code, well, you know how it works, in "public server (client cl)
{ cl.Write(); }" "client" is a know class name, but if somebody write a
custom start class (like client) and it call to "server" the type of the
start class can be change (ie public class client"s")

At this instance, how can i pass the class client to server if the name
(better type) of the parent is unknow?

public class client : Windows.Forms.Form {
public client{ new server(this); }
public Write { System.Console.Write("HI"); }
}

public class server {
public server (client cl) { cl.Write(); }
// public server (can_be_any_name cl) { cl.Write(); }
}
 
Hi smeagol:

One approach to take is to design a base class or interface from which
all client classes must derive. Then the server code does not need to
know what the name of the type is you are passing in, it only needs to
know that whatever type comes in will be derived from the base class
you designed, or implement the interface you provided.

For example, with an interface, define the interface all client's must
support:

public interface IClient
{
void Write();
}

The server will require an object implmenting IClient:

public class Server
{
public Server (IClient client) { client.Write(); }
}

Whoever writes a client must implement the interface:

class FooClient : IClient
{
public void Write()
{
// this is one implementation
}
}

class BarClient : IClient
{
public void Write()
{
// this is another implementation..
}
}

This should achieve what you need to do. As for deciding between using
an interface versus a base class, you can search for "When to Use
Interfaces" on MSDN.

HTH,
 
Back
Top