Reputation: 203
I am receiving objects using wcf, each object is different and I would like to instead of creating an object for each received object so I can manipulate it, to pass/copy each received object to only one shapeless object each time. It there such a thing?
A pseudo-code example:
Shapeless_object = received_obj_A;
if (Shapeless_object.name = "I_dont_know") {
Shapeless_object.count++;
}
Shapeless_object = received_obj_B;
if (Shapeless_object.name = "I_dont_know_too") {
Shapeless_object.count--;
Shapeless_object.age = 20;
}
received_obj_A and B are different with different parameters but passed in a single object. I hope I made my question as clear as possible.
Upvotes: 1
Views: 211
Reputation: 192
Do you mean this?
var a = received_obj_A;
if (a.name = "I_dont_know") {
Shapeless_object.count++;
}
var b = received_obj_B;
if (b.name = "I_dont_know_too") {
Shapeless_object.count--;
Shapeless_object.age = 20;
}
Dont use the base object here, because you need to check for the instance and try to cast it.
Don't do:
object a = received_obj_A; // Here you need to cast
if (a.name = "I_dont_know") {
Shapeless_object.count++;
}
object b = received_obj_B; // Here you need to cast
if (b.name = "I_dont_know_too") {
Shapeless_object.count--;
Shapeless_object.age = 20;
}
Upvotes: 0
Reputation: 4974
You could cast them to dynamic
, but it would be a performance hit.
dynamic shapeless = received_obj_A;
if (shapeless .name = "I_dont_know") {
shapeless.count++;
}
shapeless = received_obj_B;
if (shapeless.name = "I_dont_know_too") {
shapeless.count--;
shapeless.age = 20;
}
Note that you do lose static typing, obviously.
Upvotes: 1
Reputation: 1063413
You mention WCF origins: it is easy to add interfaces to WCF types via partial class
: just declare the common interface - perhaps:
interface ICommon {
string name {get;}
// ...
}
Then tell the compiler to infer the interface for each of your WCF types:
namespace TheWcfNamespace {
partial class SomeWcfType : ICommon {}
partial class AnotherWcfType : ICommon {}
partial class WhateverWcfType : ICommon {}
}
As long as SomeWcfType
etc all have the members to implement the interface, you can now treat all your WCF objects as ICommon
.
Alternatively, you might be able to do what you want here via dynamic
- just replace Shapeless_object
with dynamic
- however, that seems an abuse of the intent. A more classic implementation here would be interfaces:
if(obj is IDontKnow) {
// TODO: access as an IDontKnow
}
if (obj is IDontKnowToo) {
// TODO: access as an IDontKnowToo
}
You can of course combine this with the partial class
approach mentioned above.
Upvotes: 3