AskMe
AskMe

Reputation: 2561

Add class members and data members of constructor to a list in c#

I have class like this:

public class X
{
    public X()
    {
        Comments = new List<Y>();

    }

    [DataMember(Order = 0)]
    public string Key;

    [DataMember(Order = 1)]
    public List<Y> Comments;     
}

[DataContract]
public class Y
{
    [DataMember(Order = 0)]
    public string Body;

    [DataMember(Order = 1)]
    public string Author;
}

Here is how I'm adding to list.

private List<X> Method(string result)
{
   List<X> ret = new List<X>
   List<X> temp = new List<X>
        { 
             new Y()
            {
                Body = Body,
                Author = Author
            },

            new X() {

            Key = issueKey,

            }  
        };
    ret.Add(temp);
    return ret;
  }

Am I doing something wrong? I'm getting error: Add for collection initializer has some invalid arguments, Please suggest how to resolve this?

Upvotes: 0

Views: 59

Answers (2)

ehh
ehh

Reputation: 3480

private List<X> Method(string result)
    {
        List<X> ret = new List<X>();
        X temp = new X
        {
            Comments = new List<Y>
            {
                new Y() { Author = "Author", Body = "Body" }
            },
            Key = "issueKey"
        };

        ret.Add(temp);
        return ret;
    }

Upvotes: 1

Rowland Shaw
Rowland Shaw

Reputation: 38130

Y is not an X so cannot be added to a List<X>

Upvotes: 0

Related Questions