What's a neat solution to get property values ββfrom two classes (that have the same property names) that don't use inheritance?
Basically I have to use a poorly implemented web service supported by other programmers. They have two classes that are not derived from the parent class, but have the same properties (Ughh ...). So this looks like in my web service proxy file:
public partial class Product1
{
public int Quantity;
public int Price;
}
public partial class Product2
{
public int Quantity;
public int Price;
}
So what's the best way to grab values ββfrom known properties without duplicating code? I know I can probably use reflection, but that can get ugly. If there is an easier and crazier way to do this (perhaps in newer C # features?) Please let me know.
a source to share
I'm not sure I fully understand your situation, but maybe something like this? Define an interface IProduct
with methods getQuantity
and getPrice
and implement it in both classes:
public partial class Product1 : IProduct
{
public int Quantity;
public int Price;
public int getQuantity() { return Quantity; }
public int getPrice() { return Price; }
}
And similarly for the other; then just use them like IProduct
.
a source to share
If the classes are generated from a web proxy, you can implement a partial class that implements the common interface.
From the proxy generator:
public partial class Product1 {
public int Quantity;
public int Price;
}
public partial class Product2 {
public int Quantity;
public int Price;
}
Hand written:
public interface IProduct {
int Quantity { get; }
int Price { get; }
}
public partial class Product1:IProduct {
int IProduct.Quantity { get { return Quantity; } }
int IProduct.Price { get { return Price; } }
}
public partial class Product2:IProduct {
int IProduct.Quantity { get { return Quantity; } }
int IProduct.Price { get { return Price; } }
}
Both classes now implement IProduct
and can be passed in the same way.
a source to share
here is some pseudocode, sorry for not working. Perhaps this gives you the right direction:
Object list = new list (); objects.Add (p1); // your first product object objects.Add (p2); // your second product object
foreach (var o in objects)//go through all projects
{
if (o.GetType().Equals(typeof(Product1)) //check which class is behind the object
((Product1)o).Price = 2; //convert to fitting class and call your property
//....
}
a source to share