Not long ago I clashed with following code:
namespace Test
{
class A
{
public object mVal = new B();
};
class B
{
public string mVal = "ValueB";
};
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
a.mVal = a.mVal + b.mVal;
}
}
}
At first I wondered how it was compiled.
At second do you mean what value will assigned to a.mVal? The answer is: "Test.BValueB". I'll trying to explain what happened in this code. b.mVal type is 'string' but a.mVal type is 'object', and types casting problem resolved by C# through call a.mVal.ToString(). I.e we have expression:
a.mVal = a.mVal.ToString() + b.mVal
In other words System.Object casts to System.String implicitly and result string reference assigned to System.Object again. Real trouble is C# compiler doesn't write any errors or warnings about danger of types casting safety.
Open question is: "Where is types casting safety in .NET?"
понедельник, 18 августа 2008 г.
Подписаться на:
Комментарии к сообщению (Atom)
0 коммент.:
Отправить комментарий