Initializing an object does not work for me

What am I missing here? I expected the following to work 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 message on the symbol { on each of the last three lines:

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

I do not use Object Initializer ? Why does it accept a collection initializer? (I am using Visual Studio 2012.)

+4
source share
1 answer

To use the object initializer, you must specify which properties you want to set:

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

So, transforming all your initialization into a collection initializer, we get:

 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 can 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 only be:

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

If you feel you want to indicate what each argument means (or some of them) and you use C # 4, you can use named arguments, for example.

  new ProposalFileInfo(1, isSupportDocument: false), 
+8
source

Source: https://habr.com/ru/post/1436700/


All Articles