Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net Object Initialiser List(Of T)

Tags:

syntax

vb.net

I have been looking at some C# code:

List<Employee> Employees = new List<Employee>{
    new Employee{firstname="Aamir",lastname="Hasan",age=20},
    new Employee{firstname="awais",lastname="Hasan",age=50},
    new Employee{firstname="Bill",lastname="Hasan",age=70},
    new Employee{firstname="sobia",lastname="khan",age=80},  
    };

Now when I convert this to vb.net

Dim Employees as List(Of Employee) = New List(Of Employee)() With { New Employee() With { _  
.firstname = "Aamir", _  
.lastname = "Hasan", _   
.age = 20 _  
}, _  
New Employee() With { _  
.firstname = "awais", _  
.lastname = "Hasan", _  
.age = 50 _  
}, _  
New Employee() With { _  
.firstname = "Bill", _  
.lastname = "Hasan", _  
.age = 70 _  
}, _  
New Employee() With { _  
.firstname = "sobia", _  
.lastname = "khan", _  
.age = 80 _  
} _  
}  

I get the error "Name of field or property being initialized in an object initializer must start with'.'."

Now I can get an array of employee using the code:

Dim Employees = { New Employee() With { _  
.FirstName = "Aamir", _  
.LastName = "Hasan", _   
.Age = 20}, _  
New Employee() With { _    
.FirstName = "Awais", _   
.LastName = "Hasan", _  
.Age = 50}, _
New Employee() With { _
.FirstName = "Bill", _ 
.LastName = "Hasan", _  
.Age = 70 _
} _  
}    

But I would like a List(Of Employee) as it is bugging me as to why this doesnt work in vb.net?

like image 411
Tim B James Avatar asked Jul 15 '10 09:07

Tim B James


People also ask

How do you initialize an object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

What is list in VB net?

The List class is used to store generic types of collections objects. By using a generic class on the list, we can store one type of object. The List size can be dynamically different depending on the need of the application, such as adding, searching or inserting elements into a list.


1 Answers

Collection initialisers were added in VB.NET 2010. This is air code, but here goes:

Dim Employees as List(Of Employee) = New List(Of Employee)() From
{ 
    New Employee() With { _   
       .firstname = "Aamir", _
       .lastname = "Hasan", _ 
       .age = 20 _   
    }, _
   New Employee() With { _  
       .firstname = "awais", _  
       .lastname = "Hasan", _ 
       .age = 50 _ 
    }, _ 
   New Employee() With { _ 
       .firstname = "Bill", _ 
       .lastname = "Hasan", _ 
       .age = 70 _ 
    }, _  
   New Employee() With { _ 
       .firstname = "sobia", _ 
       .lastname = "khan", _ 
       .age = 80 _ 
    } _ 
}   
like image 83
MarkJ Avatar answered Sep 27 '22 21:09

MarkJ