cast as your expected instead of as the language grammar expected

Coordinator
Feb 18, 2014 at 3:18 PM
Edited Feb 18, 2014 at 3:24 PM
.net framework provides implicit and explicit casting support, but since CLI is working on type erasure (the template meta will be erased or replaced as the constraint when compile time). so it's impossible to cast between two unknown types. an example is as following function
bool Convert<T, T2>(List<T> l, out List<T2> r) { }
since there is no relationship between T and T2, .net framework does not allow to do the casting as
r.Add((T2)l[i]);
and it's impossible to write a function to convert a generic template to another even you have provided explicit / implicit conversion between the real types used during run-time.
so you properly need to write
bool Convert(List<int> l, out List<string> r) { }
bool Convert(List<int> l, out List<long> r) { }
bool Convert(List<Class1> l, out List<Class2> r) { }
but in fact the logic in these functions may almost be the same.

so to make the generic programming friendly, runtime casting is one of the must-have component in .net based system.

basically, the casting is working in the following orders,
  1. cast as nothing, if the source is null <nothing in vb.net>, will directly output a null. the valuetype / struct will not be impacted.
  2. DirectCast, almost the same as 'as' in c#, if the source and target has inherit / implement relationship, will output the same instance as source
  3. if on mono, try to use Convert.ChangeType. it's a bug in mono, which cause the trouble.
  4. CType, almost the same as (T)(dynamic) in c#, it can handle some internal types as IConvertible.
  5. run-time casting, it will try to find the implicit / explicit conversion functions provided in both input and output types, and run the cast function to do a run-time casting, and output a new instance. the conversion function selection is cached, so to two known types, the conversion function selection logic will only run once.
the source code is at https://geminibranch.codeplex.com/SourceControl/latest#osi/root/connector/cast.vb, while the test case at https://geminibranch.codeplex.com/SourceControl/latest#osi/root/tests/connector/cast/cast_test.vb can show the scenarios it supports.