C# inheritance question from a C++ coder

  • Thread starter Thread starter darksquid42
  • Start date Start date
D

darksquid42

Hi folks,

I'm trying to do the C# equivilent of the following and it's driving
me up the wall.

// assign base-class portion of an object to a given reference
class base
{
public:
int a;
};

class derived : public base
{
public:
int b;
};

void main(void)
{
derived d;

d.a = 10;
d.b = 20;

base b;
b.a = 30;

((base&) d) = b; d.a becomes 30
}

This comes up b/c I need access to the Client property of a TcpClient
and (unchangable) code I'm interfacing with passes me an already
connected TcpClient. I simply want to do something like this:

class TcpClientEx:TcpClient
{
TcpClientEx(TcpClient alreadyConnectedClient)
{
((TcpClient)this) = alreadyConnectedClient; // won't
compile
}

Socket getClient() { return Client; }
}

I feel like I'm missing something obvious -- can somebody help me out?

Thanks!!

larry
 
Hi,
((TcpClient)this) = alreadyConnectedClient; // won't
compile

The assignment operator assigns references (that is, pointers) in C#. To the
best of my knowledge, it is impossible to overload the "=" operator to clone
a class instance. The .NET Framework has a special way to do that - the
Clone method. Please refer to MSDN on Clone() and ICloneable().
 
Hi Larry,

Hi folks,

I'm trying to do the C# equivilent of the following and it's driving
me up the wall.
This comes up b/c I need access to the Client property of a TcpClient
and (unchangable) code I'm interfacing with passes me an already
connected TcpClient. I simply want to do something like this:

class TcpClientEx:TcpClient
{
TcpClientEx(TcpClient alreadyConnectedClient)
{
((TcpClient)this) = alreadyConnectedClient; // won't
compile
}

Socket getClient() { return Client; }
}

I feel like I'm missing something obvious -- can somebody help me out?

The thing you're missing is that C# is more type-safe than C++.
Actually, you can't do this for two reasons.

1. "this" is not assignable, ever.
2. You cannot assign an instance of a super-type to a variable of a
sub-type.

Regards,
Dan
 
The only way you can get the Client out of the TcpClient object is either to
control the instantiation of the TcpClient yourself, and return an object of
your class with something public (which is ruled out by the conditions in
your post, I guess you are probably using TcpListener), or use reflection to
pull it out.

Niall
 
Back
Top