Hi,
Im not able to get the following to explicity convert, is my cast wrong?
A a = new A();
B b = a;
A aa = (A)b;
Please correct if so...
Regards,
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Apr 8, 2011, 9:08 AM
It would also have worked if, although A didn't inherit from B, there was a user-defiined implicit conversion from A to B and an explicit conversion from B to A:
using System;
class B
{
public string Name {get; set;}
public B(A a)
{
Name = a.Name;
}
}
class A
{
public string Name {get; set;}
public static implicit operator B(A a)
{
return new B(a);
}
public static explicit operator A(B b)
{
A a = new A();
a.Name = b.Name;
return a;
}
}
class Test
{
static void Main()
{
A a = new A();
a.Name = "Neos";
B b = a;
Console.WriteLine(b.Name);
A aa = (A)b;
Console.WriteLine(aa.Name);
Console.ReadKey();
}
}
However, you'd only do this if there was a strong relationship between A and B falling short of inheritance. My example is, of course, artificial.
For instance, you have this sort of thing between the 'int' and 'long' types though these are structs and so not capable of an inheritance relationship in any case.
CrishPosted Apr 9, 2011, 5:26 AM
VulpesPosted Apr 8, 2011, 11:18 AM
However, as it's an implicit conversion I thought I'd make it a bit 'cosier' with a constructor relationship :)
Posted Apr 8, 2011, 11:14 AM
I have analysed your code example and have a question if I may...
Given the below snippet,
class A
{
public string Name {get; set;}
public static implicit operator B(A a)
{
return new B(a);
}
public static explicit operator A(B b)
{
A a = new A();
a.Name = b.Name;
return a;
}
How comes
public static implicit operator B(A a)
{
return new B(a);
}
Wouldnt need to have the same implementation as
public static explicit operator A(B b)
{
A a = new A();
a.Name = b.Name;
return a;
}
i.e making...
public static implicit operator B(A a)
{
B b = new B();
b.Name = a.Name;
return b;
}
Regards
Posted Apr 8, 2011, 8:46 AM