2

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;
            }
        }  
3
  • This would be a good example of when to use dynamic types??? Commented Jun 6, 2012 at 2:18
  • 1
    I don't believe you can do that using anonymous lists. Perhaps you could create a DTO class to contain your productId and title values? Commented Jun 6, 2012 at 2:18
  • @dreza: I think that a DTO would be a better idea. Much better for type-safety! Commented Jun 6, 2012 at 2:19

1 Answer 1

2

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;}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.