Reputation: 301
I have two class of A & B, I want to pass var type variable by a method Separation()
that is in another class. I do some casting but I receive InvalidCastException
error. Any idea how to fix this, please?
Class A{
var products =from u in XDoc.Descendants("product")
select new
{
Urunkod = u.Element("productId"),
UrunAdi = u.Element("title"),
};
XmlUrun.Separate(products);
}
Class B{
internal static void Separate(object products)
{
var o2 = CaseByExample(products, new
{
Urunkod = "",
UrunAdi = "",
});
}
public static T CaseByExample<T>(this object o, T type)
{
return (T)o;
}
}
Upvotes: 2
Views: 539
Reputation: 156459
An anonymous type cannot be passed in a strong manner outside the scope of an individual method, because there is no way to represent it outside the method's scope.
You can either use a dynamic
type (which I don't recommend), or create a named class to represent the type (which I do recommend).
public class A
{
public void Foo()
{
var products =from u in XDoc.Descendants("product")
select new C
{
Urunkod = u.Element("productId"),
UrunAdi = u.Element("title"),
};
}
}
public class B
{
public void Bar(IEnumerable<C> cList)
{
foreach(var c in cList)
Console.WriteLine(c.Urunkod);
}
}
public class C
{
public XElement Urunkod {get;set;}
public XElement Urunkadi {get;set;}
}
Upvotes: 2