Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Initialization Not Working for Me

What am I missing here? I expected the following to work just fine:

public class ProposalFileInfo
{
    public int FileId { get; set; }
    public bool IsSupportDocument { get; set; }
}

// ...

var attachments = new List<ProposalFileInfo>();

attachments.Add(new ProposalFileInfo { 1, false });
attachments.Add(new ProposalFileInfo { 2, false });
attachments.Add(new ProposalFileInfo { 3, false });

Instead I get an error at the { character on each of the last three lines:

Cannot initialize type 'xxx.yyy.ProposalFileInfo' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Am I not using an Object initializer? Why does it assume a collection initializer? (I'm using Visual Studio 2012.)

like image 318
Jonathan Wood Avatar asked Feb 20 '23 00:02

Jonathan Wood


1 Answers

To use an object initializer you have to specify which properties you want to set:

attachments.Add(new ProposalFileInfo { FileId = 1, IsSupportDocument = false });

So converting your whole initialization into a collection initializer, we end up with:

var attachments = new List<ProposalFileInfo>
{
    new ProposalFileInfo { FileId = 1, IsSupportDocument = false },
    new ProposalFileInfo { FileId = 2, IsSupportDocument = false },
    new ProposalFileInfo { FileId = 3, IsSupportDocument = false },
};

However, you could make your code simpler by simply adding a constructor to ProposalFileInfo:

public ProposalFileInfo(int fileId, bool isSupportDocument)
{
    FileId = fileId;
    IsSupportDocument = isSupportDocument;
}

Then your initialization can just be:

var attachments = new List<ProposalFileInfo>
{
    new ProposalFileInfo(1, false),
    new ProposalFileInfo(2, false),
    new ProposalFileInfo(3, false)
};

If you feel you want to specify what each argument means (or some of them), and you're using C# 4, you can use named arguments, e.g.

    new ProposalFileInfo(1, isSupportDocument: false),
like image 125
Jon Skeet Avatar answered Feb 26 '23 21:02

Jon Skeet