Imagine having an integer
var aaa = (int)1; -------> here I have an int
var bbb = (object)aaa;-----> bbb is an object but the type is kept...
var ccc = aaa.GetType();---> ... in fact here I still have an integer
now I define a new variable
var ddd = (object)2;
and I want to cast it to the same type as aaa. ccc is a type and it's type integer but I can't do
var ddd = (ccc)2;
So what puzzles me is how to box a 1st variable and then unbox a 2nd variable according to the type of the 1st variable
Obiviously I did it here with int but the matter can be extended to whatever class type.
Thanks in advance
Patrick
You cannot strongly type a variable at runtime. The advantage of a strong type (here
int) versus a week type (object) is that you know at compile time (or design time) which members an object has and which operations you can apply to it. E.g., you know that you can write5 * aaaifaaais anint. You cannot do that with astring.aaa.GetType()yields aSystem.Typeobject at runtime! You cannot use it to cast another object. Well, you could write something likebut to what do you want to assign it? The type of
dddis unknown at compile time and the only possible type you can write in your code isobjectagain. And btw.,ChangeTypereturns anobject. What else could it return?Note that the
varkeyword does not help.vartells the compiler to infer the (strong) static type (which it does of course at compile time). If you hover the mouse over such a variable, the Visual Studio editor will reveal you the concrete typevarstands for.Generic types are always resolved at compile time. They do not help either.
With a limited number of possible types, you can use a switch expression or switch statement to do appropriate things depending on the type.
This uses type test patterns.
With class types this is a bit different. Here you can use Polymorphism. This works in a limited way with value types (structs) if they implement interfaces.
The idea behind polymorphism is that you do not need to know the concrete type of an object to do meaningful things with it. Example:
Given these declarations, you can write:
and
You do not need to know what kind of shape you have, to determine its area. If you implement new shapes in future, the
PrintAreamethod and the foreach-loop will not have to be adapted.