I’m trying to learn how from this site http://msdn.microsoft.com/en-us/library/cc265158(v=vs.95).aspx but the code won’t compile and i get tons of errors.
Here’s my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bail
{
public class ListboxMenuItem
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public ListboxMenuItem(String firstName, String lastName, String address)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
}
}
class ListboxMenuItems
{
List<ListboxMenuItem> Items;
Items = new List<ListboxMenuItem>();
Items.Add(new ListboxMenuItem("Michael", "Anderberg", "12 North Third Street, Apartment 45"));
Items.Add(new ListboxMenuItem("Chris", "Ashton", "34 West Fifth Street, Apartment 67"));
Items.Add(new ListboxMenuItem("Cassie", "Hicks", "56 East Seventh Street, Apartment 89"));
Items.Add(new ListboxMenuItem("Guido", "Pica", "78 South Ninth Street, Apartment 10"));
}
}
All errors are with Items
For example Items = new List<ListboxMenuItem>(); produces the error
Error 1 Invalid token ‘=’ in class, struct, or interface member declaration ListboxMenuItems.cs 26 15 Bail
At first I only corrected the error, however after seeing the link I noticed the old answer doesn’t really help.
You can still find it on the bottom though.
The New Answer
I have just looked at the link, and it seems like you’re doing the wrong thing anyway.
You need your class to inherit from
ObservableCollection<T>, and instead of aListfield/property you should be using the functionality of the base class (which already hasAddmethod):All of this is clearly written in the reference you provided so you should be more careful with adopting code from documentation.
The Old Answer
You have put the initialization code right inside the class declaration, where normally methods, fields and properties are placed.
Initialization code is placed in a special method called ‘constructor’ that has the same name as the class, doesn’t have a return type, and is placed inside of the corresponding class:
I changed
Itemsfrom being a field to a property. This is a better practice because you can specify who can change it (in our case,private setallows to set it only from withinListboxMenuItems).I also used list initializer syntax that allows you to drop many
Addcalls in favor of a cleaner, clutterless syntax.