Reputation: 181
Why in C# 3 I can do this:
DataTable dt = new DataTable() {
Columns = { "1", "2", "3" } };
But I can't do this:
class Person {
int Id { get; set; }
}
class Program {
static void Main(string[] args)
{
var v = new List<Person> { 1, 2, 3 };
}
}
Upvotes: 2
Views: 51
Reputation: 36583
Because there is not implicit conversion from int to Person. If you were to define an implicit conversion for Person, that should work:
http://msdn.microsoft.com/en-us/library/z5z9kes2(v=VS.100).aspx
Note in the example that a double value is implicitly convertable to a Digit type. You could define an implicit conversion for int to Person.
Upvotes: 4
Reputation: 202
You need to call the constructor to actually instance it. In your code you are basically saying that Person is of type int and this is not the case, the variable inside is.
You can do something like this to achieve what you want.
var v = new List<Person>() { new Person(1), new Person(2), new Person(3) };
Given that you have a constructor that accepts an int.
Like this one:
public Person(int id)
{
Id = id;
}
Upvotes: 0
Reputation: 38543
Because and integer is not the same as a Person
object, and the Id
is a property that needs to be assigned to.
var v = new List<Person>();
for (i = 1; i <= 3; i++) {
var p = new Person() {
Id = i;
}
v.Add(p);
}
Upvotes: 0
Reputation: 48596
Neither 1, nor 2, nor 3 are Person objects.
You could, though try:
var people = new List<Person>() { new Person() { Id = 1 }, new Person() { Id = 2 } , new Person() { Id = 3 } };
Upvotes: 0