I wanted to know if there is a syntax to add named objects to a list in its declaration so the end result is a list of objects that I can refer to them by name (without searching).
Here's the long way (which I know works), I have used a list of employees just to illustrate what I'm trying to do.
List<Employee> Employees = new List<Employee>();
Employee Tom = new Employee(id = 001, Department = "Sales");
Employee Joan = new Employee(id = 002, Department= "HR" );
Employee Fred = new Employee(id = 003, Department= "Accounting");
Employees.Add(Tom);
Employees.Add(Joan);
Employees.Add(Fred);
So the above works, I have named objects in a list which I can then use.
You can also declare the Employees when you declare the list:
List<Employee> employees= new List<Employee>()
{
new Employee() { empID = 001, Name = "Tom", Department= "Sales"},
new Employee() { empID = 004, Name = "Joan", Department= "HR"},
new Employee() { empID = 003, Name = "Fred", Department= "Accounting" },
};
However, I have to create the Name as a string in the class, instead of the Employee object.
What I want to know is, "Is there a way to do this?"
List<Employee> employees= new List<Employee>()
{
new Employee() Tom = { empID = 001, Department= "Sales"},
new Employee() Joan = { empID = 024, Department= "HR"},
new Employee() Fred = { empID = 023, Department= "Accounting" },
};
^^Obviously, the above doesn't work, but hopefully it shows what I am trying to achieve.
Edit: thanks for the answers @Ann L and D Stanley, I think I need to elaborate further on where I'm trying to put, your example works here:
<script runat="server">
Employee Tom = new Employee(001, "Sales");
Employee Joan = new Employee(002, "HR");
Employee Fred = new Employee(003, "Accounting");
public List<Employee> Employees;
protected override void OnLoad(EventArgs e)
{
Employees = new List<Employee>() { Tom, Joan, Fred };
base.OnLoad(e);
}
</script>
So that my list is publicly accessible, however, it defeats my goal of having the declaration and assignment in the same place, as the below does NOT work
<script runat="server">
Employee Tom = new Employee(001, "Sales");
Employee Joan = new Employee(002, "HR");
Employee Fred = new Employee(003, "Accounting");
public List<Employee> Employees = new List<Employee>() { Tom, Joan, Fred };
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
</script>
On the above, I get the error "A field initializer cannot reference the non-static field, method or property"
Dictionary<string, Employee>.employees = new List<Employee> { Tom, Joan, Fred }