Let's say I have a class called Company
public class Company
{
public string name;
public string id;
}
I have a list called CompanyList
var companyList = new List<Company>();
I would like to assign name = "Company A", id = "001" to this empty companyList
variable.
How do I do so?
companyList.FirstOrDefault().Name = "Company A";
companyList.FirstOrDefault().Id = "001";
Before you can assign a value to a company in a collection, you must add a company to the collection. You are setting the values of that company, not of the collection itself.
Use either:
var companyList = new List<Company>();
companyList.Add(new Company { Name = "Company A", Id = "001" });
Or:
var companyList = new List<Company>();
companyList.Add(new Company());
// Assumes you want to modify the first company in the list
companyList[0].Name = "Company A";
companyList[0].Id = "001";
You could use collection initializer:
var companyList = new List<Company>{ new Company { Name = "Company A", Id = "001" } };
effectively the same as bellow, a bit more compact
var companyList = new List<Company>();
companyList.Add(new Company { Name = "Company A", Id = "001" });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With