Casting between inherited classed - c#

The following cast doent work. I think it should, can you explain to me why not? Both WebserviceErrorMessage and BTMacResponse inherit from the WebserviceMessage class
DataLayer.WebserviceMessage msg = new Service.WebserviceErrorMessage(ex) ;
DataLayer.BTMacResponse macrsp = (DataLayer.BTMacResponse)msg;

Unless WebserviceErrorMessage inherits from BTMacResponse, I don't see why this should work. You're trying to cast a value to BTMacResponse when the object simply isn't a BTMacResponse.
To put it another way, would you expect to be able to cast a FileStream to a MemoryStream just because they both inherit from Stream?
Would you expect to be able to cast a Button to a String just because they both inherit from Object?

You can't cast that way. The following is illegal:
class Base {
}
class A : Base {
}
class B: Base {
}
Base someBase = new A();
B someB = (B)someBase;

You cannot cast down the hierarchy because when you create an object of the parent, you do not create the child object with it, however when you create an object of the child an instance of the parent is created, thats why you can upcast and not downcast.
in your case you can cast DataLayer.WebserviceMessage to its children and not the opposite.

there is no contractor for DataLayer.BTMacResponse that get DataLayer.WebserviceMessage as a parameter you need to implement this:
public BTMacResponse(WebserviceMessage w)
{
// copy stuff to 'this'
}
public static implicit operator BTMacResponse(WebserviceMessage w)
{
BTMacResponse b = new BTMacResponse(w);
return b;
}

Related

Cast derived class to another derived in c#

I have a base class :
interface IBaseClass{
int x;
int y;
baseClass someMethod();
}
and some derived class :
class dClass1 : IBaseClass {
int x;
int y;
baseClass someMethod();
}
class dClass2 : IBaseClass {
int x;
int y;
baseClass someMethod();
}
The value of property according to the subclass algorithm is different from other subclass
now i want cast these subclass to them:
dClass1 c1=new dClass1 ();
c1.x=4;
c1.y=5;
dClass2 c2=c1;//cast to dClass2 , but value of property set by according to the own algorithm
Console.WriteLine("{0}, {1}", c1.x, c1.y);//4,5
Console.WriteLine("{0}, {1}", c2.x, c2.y);//7,1
First off, lets make it clear that IBaseClass is not a base class, its an interface, which is something quite different. Pointing out the differences is not in the scope of this answer but you can easily read about it, starting here.
That said, as others have stated, you can't do what you want directly. Consider the canonical example IAnimal, Dog, Cat, etc. Evey dog and every cat are animals, but cats are not dogs and dogs are not cats and you are basically asking a cat to be a dog; you first need to teach cats how to dogify (they won't do that out of the box for you).
In order to achieve this behavior there are quite a few ways how you can do it:
User defined cast: You can define operators that convert from one class to another. If you make them implicit you'd even get your code to compile as it is right now:
public static implicit operator dClass2(dClass1 obj)
{ //logic to convert obj to corresponding new dClass2 instance }
Now this would be legal:
var c1 = new dClass1();
dClass2 c2 = c1; // implicit cast operator is called.
Note that if you were to implement the cast operator as explicit, the former code would not compile. You would need to explicitly cast c1:
var c2 = (dClass2)c1;
Define a dClass2 constructor that takes a dClass1 argument:
public dClass2(dClass1 obj) { ... }
and you'd write the following code:
var c1 = new dClass1();
var c2 = new dClass2(c1);
Define a static factory method in dClass2 that takes a dClass1 argument and produces a new dClass2 instance:
public static dClass2 CreateFrom(dClass1 obj) { ... }
And the corresponding code:
var c1 = new dClass1();
var c2 = dClass2.CreateFrom(c1);
Many more I haven't bothered to think about...
Which one you choose is up to personal taste. I'd probably use the explicit cast, but there is nothing inherently wrong with any of the options available.
dClass1 and dClass2 are two different types. You can't directly cast one to the other. You'd have to convert one to the other. For example:
dClass1 c1 = new dClass1
{
x=4,
y=5
};
dClass2 c2 = new dClass2
{
x = c1.x,
y = c1.y
};
Or, using multiple lines like your original code:
dClass1 c1 = new dClass1();
c1.x=4;
c1.y=5;
dClass2 c2 = new dClass2();
c2.x = c1.x;
c2.y = c1.y;
The point is, the system has no way to directly cast one type to another type. You can encapsulate this conversion into factory methods on either type, or on separate classes. But casting isn't an option. Just because the two types have members of the same type/name/etc. doesn't make them the same type.
What you're trying to do isn't possible. You can cast an object to a less (or more in some cases) derived type, but you can't cast an object to another type unless you define a custom cast on the type.
You can read about defining custom casts here: https://msdn.microsoft.com/en-us/library/ms173105.aspx

Force type cast between classes of different namespaces

How Force type cast between classes of different namespaces.
Both namespaces have same class.
You can't cast an object to a type it is not. If it belongs to a different namespace then it is not the same class. You will have to create a converter:
public static Namespace1.SomeClass Convert(Namespace2.SomeClass someClass) {
Namespace1.SomeClass rtn = new Namespace1.SomeClass();
rtn.SomeProp = someClass.SomeProp;
rtn.SomeOtherProp = someClass.SomeOtherProp;
return rtn;
}
you could even use reflection to set all the properties on Namespace1.SomeClass that have the same name as Namespace2.SomeClass.
Also, if you own the code to one of the classes, you can check into overloading explicit and implicit on your class.
You can create generic Converter so you don't have to do this each time you need to cast a different type of objects,
T ConvertObject<T>(object M) where T : class
{
// Serialize the original object to json
// Desarialize the json object to the new type
var obj = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(M));
return obj;
}
// Test ObjectToCast is type Namespace1.Class, obj is Namespace2
Namespace2.Class obj = ConvertObject<Namespace2.Class>(ObjectToCast);
Assuming that both classes are the same this will work.
You can't cast from a Type to a different Type, even if the code of the class is exactly the same.
You can create a Converter capable to convert between the two types, or provide implicit/explicit casts inside both classes implementations or eventually you can try Automapper.
You need to qualify the type:
namespace Foo
{
class Bar {}
}
namespace Baz
{
class Bar {}
}
Foo.Bar x = new Foo.Bar();
Baz.Bar y = (Baz.Bar)x;
Of course, this will fail unless there is a conversion defined.
This is not possible. A type include its namespace as part of its full name.
Its like the town of Springfield: same name but from different states. They are all different.
A possible approach would be to overload the cast operator of one of the type so that they can be cast into another type. It won't be a real cast, as the result will be to create a new object with the same value.
public static explicit operator Massachusetts.Springfield(Illinois.Springfield town)
{
return new Massachusetts.Springfield(town); // or any other code to copy the fields from one type to the other
}
If both classes are serializable, you can serialize the first object to XML, change the "namespace" in the xml and deserialize it again.
The fact that the two classes have the same name doesn't mean anything to the compiler. You may have Foo.Orange and Bar.Orange, but to the compiler it may as well be Apple and Orange. To convert:
namespace Foo
{
public class Orange{}
public static explicit operator Foo.Orange(Bar.Orange) { // conversion code }
}
namespace Bar
{
public class Orange{}
public static explicit operator Bar.Orange(Foo.Orange) { // conversion code }
}
// somewhere else
Foo.Orange o = new Foo.Orange();
Bar.Orange bar = (Bar.Orange)o; // and vice-versa

Casting between classes that share the same interface

I have two interfaces IHeaderRow, and IDetailRow
I then have an object that implements both RawRow:IHeaderRow, IDetailRow
I then need to cast it to HeaderRow which implements IHeaderRow.
But when I try, it ends up being null or giving an exception.
I can cast ObjectRawRow to either interface IHeaderRow, or IDetailRow
var ObjectIHeaderRow = ObjectRawRow as IHeaderRow;
var ObjectIDetailRow = ObjectRawRow as IDetailRow;
But I can not cast ObjectRawRow to HeaderRow , or ObjectIHeaderRow to HeaderRow.
It throws the error Cannot convert source type 'IA' to target type 'A'
I need to cast it into the actual class HeaderRow.
Thoughts?
EDIT:
Even though setting up an explicit cast took care of the issue I thought I'd provide an answer to the people wondering, WHY I was doing what I was.
In short, I'm sequentially processing a file. Line by line. I read the row into RawRow, and until I look at a few values, I don't actually know what type of row it is going to be. I then wanted to cast it to the proper type.
You can only implicitly cast objects to types they inherit from or implement - since RawRow doesn't derive from HeaderRow, it's not possible.
Depending on your requirements, you could overcome this by writing an explicit conversion operator, creating a HeaderRow constructor that accepts a RawRow as its prototype, or by modifying your code to operate on an IHeaderRow.
Why do you need to cast it to a HeaderRow in the first place? If IHeaderRow produced the api that a HeaderRow implements, than you should just be able to act on IHeaderRow "objects" using the defined methods.
The point of an interface is so that you can treat a grouping of different objects as a similar type. Not so that you can cast different objects between classes that are not linked by inheritance.
First, why do you need to do such a weird cast? There's probably another design for what you're trying to do.
Second, the reason you can't do the cast is because a RawRow isn't an HeaderRow. The only guarantee it makes is that it implements IHeaderRow. The problem is that it has a bunch of other stuff too, stuff that HeaderRow doesn't have. And vice versa - HeaderRow probably has a bunch of stuff that ObjectRawRow doesn't have.
Imagine your classes look like this:
interface IHeaderRow
{
string GetText();
}
class HeaderRow : IHeaderRow
{
public string GetText()
{
return "My Label";
}
public int GetFoo()
{
return 42;
}
}
class ObjectRawRow : IHeaderRow
{
public string GetText()
{
return "My Raw Label";
}
}
Now if you do this, you're ok:
ObjectRawRow row = new ObjectRawRow();
IHeaderRow header = row as IHeaderRow;
string label = header.GetText(); // fine, since GetText is guaranteed to exist
But try this on for size:
ObjectRawRow row = new ObjectRawRow();
HeaderRow header = row as HeaderRow;
int magic = header.GetFoo(); // BOOM! Method doesn't exist,
// because the object isn't really a HeaderRow under the covers.
// It's still really an ObjectRawRow. What do you do now? Crash hard is what.
And that's why you can't cast outside of the inheritance tree.
You cannot cast ObjectRawRow to HeaderRow unless one inherits from the other.
Interfaces have nothing to do with it.
Consider:
class Shape
interface IHasCorners
class Rectangle : IHasCorners, Shape
class Triangle : IHasCorners, Shape
Rectangle myRectangle = new Rectangle();
Triangle myTriangle = new Triangle();
//upcasts
Shape s = (Shape)myRectangle;
IHasCorners hc = (IHasCorners)myRectangle;
//downcasts
Rectangle r2 = (Rectangle)s;
r2 = (Rectangle)hc;
//upcasts
s = (Shape)myTriangle;
hc = (IHasCorners) myTriangle;
//these downcasts won't work
//the variables now reference a Triangle instance
Rectangle r3 = (Rectangle)s;
r3 = (Rectangle)hc;
You will not be able to make this cast unless there is an inheritance relationship between the types. If that is not possible then the best you can do is create an explicit conversion operator that allows you to cast one type as another type.
If you do create an explicit conversion you should understand that this will be slower than casting as you will be invoking an method that will do work as opposed to casting which only changes the reference type and doesn't change any of the memory on the heap.
Consider this example that doesn't compile:
class Example
{
static void Main()
{
Foo foo = new Foo();
Bar bar = (Bar)foo;
}
}
class Foo { }
class Bar { }
Since there is no inheritance relations between the types nor is there an explicit conversion from Foo to Bar this cannot compile.
But adding an explicit conversion allows it to compile:
class Example
{
static void Main()
{
Foo foo = new Foo();
Bar bar = (Bar)foo;
}
}
class Foo
{
public static explicit operator Bar(Foo foo)
{
return new Bar();
}
}
class Bar { }
You can only cast an instance to a particular class if the object is actually an instance of that class (or is derived from that class).
It is not possible to cast an instance of class A to completely unrelated class B (which is what you're trying to do), even if they implement the same interfaces.
You can use the explicit keyword to create methods that will be called when you try to cast from IA to A. The reason it doesn't work without you writing your own method is because the compiler doesn't know what to do with the values that aren't being provided.

How to find if an object is from a class but not superclass?

In C# how can you find if an object is an instance of certain class but not any of that class’s superclasses?
“is” will return true even if the object is actually from a superclass.
typeof(SpecifiedClass) == obj.GetType()
You could compare the type of your object to the Type of the class that you are looking for:
class A { }
class B : A { }
A a = new A();
if(a.GetType() == typeof(A)) // returns true
{
}
A b = new B();
if(b.GetType() == typeof(A)) // returns false
{
}
Unfortunately this is not possible in C# as C# does not support multiple inheritance. Give this inheritance tree:
GrandParent
Parent
Child
The Child will always be an instance of every type above it in the inheritance chain.
You may want to look at a couple of methods on the Type class:
Type.IsInstaceOf
and
Type.IsSubclassOf
You can pass in the class you're looking for and get the information you need.
if(Obj.GetType() == typeof(ClassName))
This worked for me

C# - Problem with generics and inheritance

I've got a problem with inheritance and generics.
This is the code that illustrates my problem:
namespace TestApplication
{
public class MyClass<T>
{
private T field;
public MyClass(T field)
{
this.field = field;
}
}
public class MyIntClass : MyClass<int>
{
public MyIntClass(int field)
: base(field)
{
}
}
}
And when I try to do something like this:
MyClass<int> sth = new MyClass<int>(10);
MyIntClass intsth = (MyIntClass) sth;
I receive cast exception: Invalid cast exception. Unable to cast 'TestApplication.MyClass`1[System.Int32]' to 'TestApplication.MyIntClass'.
What is more I cannot create cast operator:
public static implicit operator MyIntClass(MyClass<int> myClass)
because: 'TestApplication.MyIntClass.implicit operator TestApplication.MyIntClass(TestApplication.MyClass)': user-defined conversions to or from a base class are not allowed
I need to create casts as described above. I don't know why I cannot cast from a type that is the base class. How can I solve this problem?
Thanks in advance.
Edit
Thanks for Your answers.
Now I see that i cannot convert from a base class to derived class and i see that it doesn't have anything to do with generics.
But why i cannot create user-defined conversions from a base class? I have a method that returns the base class. I am able to define a conversion method but creating a cast operator imho would be a better solution.
You can only cast from a base class to a derived class if the object is actually of type derived class. I mean, you can't cast an instance of base (MyClass<int>) to MyIntClass. You can, however cast it if it was actually of type MyIntClass stored as an MyClass<int> instance.
MyClass<int> foo = new MyIntClass();
MyIntClass bar = (MyIntClass)foo; // this works.
Assume:
class Base {
int x;
}
class Derived : Base {
int y;
}
Base foo = new Base();
Derived bar = (Derived)foo;
if it was allowed, what would the value of bar.y be?
In fact, converting from Derived to Base is not a conversion at all. It's just telling the compiler to let the variable of type Base to point to an object of type Derived. It is possible since derived has more or equal features than Base which is not the case in the other way around.
If you were able to create a conversion operator between base and derived classes, the C# compiler would be unable to distinguish it from the built in relationships defined for them. This is why you cannot create cast operators along inheritance hierarchies.
The other answers so far are correct, but I'd like to point out that your example has nothing to do with generics. It's the equivalent of:
using System;
class Base {}
class Child : Base {}
class Test
{
static void Main()
{
Base b = new Base();
// This will throw an exception
Child c = (Child) b;
}
}
In the comments you asked:
But why conversion from a base class is not allowed?
Simple - it would make no sense. Consider the example:
class BaseClass
{
public int x;
public BaseClass(int StartX)
{
this.x = StartX;
}
}
class ChildClass: BaseClass
{
public int Y;
public BaseClass(int StartX, StartY): base(StartX)
{
this.y = StartY;
}
}
class Program
{
public static void Main()
{
BaseClass B = new BaseClass(3);
ChildClass C = (ChildClass)B;
Console.WriteLine(C.y);
}
}
What do you suppose this program would output, assuming the cast worked? Even worse - imagine that BaseClass has two child classes - ChildClassA and ChildClassB. Do you want this to work?
ChildClassA A = new ChildClassA();
BaseClass bc = (BaseClass)A;
ChildClassB B = (ChildClassB)bc;
This would effectively allow to cast ChildClassA instances to ChildClassB - completely wrong.
As Mehrdad stated, you cannot downcast an object. Upcasting is implicit, therefore you cannot overwrite it.
As for the implicit operator, you can still create a constructor in the derived class which receives a parameter of type baseclass.
If you need to cast freely, define the variable as baseclass, but instantiate derived classes.
As has been said, you're trying to cast an object into a type that it doesn't derive from. Did you perhaps want to do this:
MyClass<int> sth = new MyIntClass(10);
MyIntClass intsth = (MyIntClass) sth;
Instead of creating an MyIntClass, try an alias:
using MyClass<int> = What.Ever.Namespace.MyIntClass;
This is now valid:
MyClass<int> foo = new MyClass<int>();
MyIntClass bar = (MyIntClass)foo;
Just understand that when doing the using alias, you have to qualify your namespace on the alias type name (What.Ever.Namespace).
Regarding your second question:
But why i cannot create user-defined conversions from a base class?
Well, suppose you have this scenario
class Base {
}
class Derived {
public static operator Derived(Base b) { ... }
}
and you tried to do this
Base x = new Derived();
Derived y = (Derived)x;
should the conversion be called? Of course not! The value inside x is actually of type Derived, so the cast is direct, without conversion. But if the value was not of type Derived, but a concrete Base, then the user-defined conversion has to happen because otherwise we'd have a compiler error. This all makes no sense; user-defined conversions are found in compile-time, and the type of the value of x is only known in runtime. Therefore, the compiler would not know what to do - call the user-defined conversion or simply cast the value...
Hope this makes a bit of sense to you.
Answering to your last edit.
This code does already compile, it only fails at runtime:
MyIntClass intsth = (MyIntClass) sth;
So, the following cast operator would be redundant if left explicit:
public static implicit operator MyIntClass(MyClass myClass)
So, the compiler should prevent you from adding that conversion. I think the error might be confusing, but I think it just forbids converting class B to class A if B is derived from A (the warning seemed to me to prevent any conversion to A, at first).
If the operator is made implicit, it is also dangerous, because a downcasting can always fail, so you have to:
show the compiler that you know that, by adding an explicit cast;
show the reader (which includes yourself, minutes later) that the operation might fail.
Assignment/conversion of a base class to a derived class makes sense if you consider assignment or conversion to be a value by value copy. What's confusing about c# for
newbies is the inconsistent way it does things:
'int' is a 'simple' type:
int i = 5; // <- this creates an int.
int j = i; // <- this creates another int and copies the value of i into j.
'Object' is not a simple type:
Object a; // <- this does not create a copy of 'Object', only a reference to one
Object b = new Object(); // <- this actually creates an Object
a = b; // <- this sets the reference to an object a to the reference to an object b.
// both of them reference the same Object. No values were copied.
If it were doing a copy of values then copying to base class to a derived class would
work. C# doesn't work like other languages.
I think that might be what's confusing you.

Categories

Resources