Jozef
Jozef

Reputation: 493

How to use constructor to initialize list of objects containing the array

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

Upvotes: 0

Views: 449

Answers (1)

Damian
Damian

Reputation: 2852

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" };

Upvotes: 2

Related Questions