I have two classes. The base class is A. The inherited class is B. I would like copy a base class from one object into the base class of another object without affecting the original class. However, .NET seems to ignore the copying. Is this not possible in .NET. I know this is possible in C++. I have included C++ code to illustrate what I am trying to achieve.
I understand in that in this particular example I can directly assign the value bClass.ValueA = aClass.ValueA. But what if Class A had private members? This would not be possible.
Example Classes
Public Class A
Public ValueA As String
End Class
Public Class B
Inherits A
Public ValueB As String
End Class
The Code
Dim aClass As New A
Dim bClass As New B
aClass.ValueA = "AClass"
bClass.ValueA = "BClass"
bClass.ValueB = "BClass"
Dim baseBClass As A
baseBClass = CType(bClass, A)
baseBClass = aClass
Results:
aClass.ValueA = "AClass"
bClass.ValueA = "BClass"
bClass.ValueB = "BClass"
baseBClass.ValueA = "AClass"
Intended Results:
aClass.ValueA = "AClass"
bClass.ValueA = "AClass"
bClass.ValueB = "BClass"
baseBClass.ValueA = "AClass"
C++ Explanation Comparison
#include <string>
#include <iostream>
using namespace std;
class A {
public:
string ValueA;
};
class B : public A {
public:
string ValueB;
};
int main(int argc, char *argv[]) {
A aClass;
B bClass;
aClass.ValueA = "AClass";
bClass.ValueA = "BClass";
bClass.ValueB = "Blcass";
cout << aClass.ValueA <<endl;
cout << bClass.ValueA << endl;
cout << bClass.ValueB << endl;
A *baseBClass;
baseBClass = (A*) &bClass;
*baseBClass = aClass;
cout << aClass.ValueA <<endl;
cout << bClass.ValueA << endl;
cout << bClass.ValueB << endl;
cout << baseBClass->ValueA << endl;
return 0;
}
Intended and Actual Results:
aClass.ValueA = "AClass"
bClass.ValueA = "AClass"
bClass.ValueB = "BClass"
baseBClass->ValueA = "AClass"
I do not think this is possible without pointers. I have tried
Ctype(bClass, A) = aClass
Directcast(bClass, A) = aClass
I get this Error:
Expression is a value and therefore cannot be the target of an assignment.