Good ide/ buggy code

danpbrown1973

New member
Joined
Nov 3, 2018
Messages
2
Programming Experience
3-5
Hi folks. I was wondering if anybody can tell me why my collection works just fine if I leave it in the main method, but not when I add it to the Person class that our teacher wants us to include a collection in. I get a million errors when added to that class, but it works fine in main. Picture included.
 

Attachments

  • buggycode.JPG
    buggycode.JPG
    64.6 KB · Views: 62
Code outside of method MUST be a declaration. You can initialise the declared variable but there MUST be a declared variable. Your 'mycoll.Add' lines and your 'for' loop are NOT declarations so they can NOT be outside a method.

As for the first line, the 'var' keyword relies on type inference for the type of the declared variable and that is only valid on local variables, i.e. only inside a method again. For member variables, you MUST specify the type explicitly. If you want that code to be executed when you create a Person object then you need to put it inside a constructor, otherwise you need to put it in a method that you will call later.
 
By the way, there's no need to write out your properties long-hand like that. You can just do this:
public string Name { get; set; }
public int Age { get; set; }

You only need the full implementation with explicit backing field if you want to add extra code to the getter and/or setter, e.g. validation or raising an event.
 
By the way, there's no need to write out your properties long-hand like that. You can just do this:
public string Name { get; set; }
public int Age { get; set; }

You only need the full implementation with explicit backing field if you want to add extra code to the getter and/or setter, e.g. validation or raising an event.
Ahh ok, thanks.
 
Back
Top Bottom