0

right now, I use this command to initialize a list of objects and it works fine.

public class RelatedBlog
{
    public string trekid { get; set; }
    public string imagepath { get; set; }

    public RelatedBlog(string trekid, string imagepath)
    {
        this.trekid = trekid;
        this.imagepath = imagepath;          
    }
}

trek.relatedblog = new List<RelatedBlog>            
{
   new RelatedBlog("trekid", "../Images/image.jpg"),         
};

However, lately I have decided that instead of single string as a first property, I want to have an array of several strings - with the size up to 4 (but it can be also fixed and I can enter nulls during initialization). This is the code I am using, but it doesnt work, it expects some more "(" when I call the constructor.

public class RelatedBlog
{
    public string[] trekid { get; set; }
    public string imagepath { get; set; }

    public RelatedBlog(string[] trekid, string imagepath)
    {
        this.trekid = trekid;
        this.imagepath = imagepath;          
    }
} 

trek.relatedblog = new List<RelatedBlog>            
{
   new RelatedBlog({"string1", "string2"}, "../Images/image.jpg"),         
};

Can someone advise me where I make a mistake and how to initialize this list properly. Thanks a lot

1
  • What about new List<RelatedBlog>()? Commented Feb 18, 2017 at 15:48

1 Answer 1

2

Use:

trek.relatedblog = new List<RelatedBlog>
{
    new RelatedBlog(new[] {"string1", "string2"}, "../Images/image.jpg")
};

You are using implicitly typed array, the compiler can detect the type inside array but you have to inform it that you are passing an array:

var arr1 = new[] { "hello", "world" };

is equal to

var arr2 = new string [] { "hello", "world" };
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.