1

I am trying to run the following code :

classA = classD;

to assign the values in classA to classD (the variable is being shared from another class called 'classC').

the above line would normally work in C++ but in C# its returning an error! is this possible in C#?

Ahoura Ghotbi
  • 2,866
  • 12
  • 36
  • 65

2 Answers2

2

From the comments A : D, so all A are D, but not all D are necessarily A.

So with two variables:

A classA;
D classD = ...

We need

classA = (A) classD;

This does a type-check, to confirm that the specific classD is actually also an A. If this is the case (or it is null) then the assignment is successful; otherwise an exception occurs.

This is to prevent you assigning something to classA that is actually not really an A.

Note it is implicit the other way, since the compiler knows it to be valid:

classD = classA; // always valid - no type check
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

If you are asking can you copy attributes of the same name from instances of different classes, then no.

Saying classA = classB where the classes are not related in the class hierarchy will cause a type error. If they are related, then all you are doing is changing the value of the variable classA, not copying anything.

nickd
  • 3,951
  • 2
  • 20
  • 24