1

I'm working on an application that uses a list to handle previous guesses from the user. Below is the (private) list and the property for accessing the list.

To prevent privacy leak i'm using a ReadOnlyCollection, which is also the reason for me only having a getter in the property (elements are added inside the class directly to the list, not through the property).

Now to the problem. The code below generates to error message:

  1. TheNameOfTheClass.PreviousGuesses.get must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.
  2. Cannot implicity convert type 'System.Collections.Generic.List' to 'System.Collections.ObjectModel.ReadOnlyCollection.

How can this be solved? Thanks in advance!

private List<int> _previousGuesses;

public ReadOnlyCollection<int> PreviousGuesses {
    get {
        return _previousGuesses;
    }
}

EDIT: Ok, so problem nr 2 is solved (thanks Zortkun!). What about the first problem, that I can't use only a getter, any ideas?

holyredbeard
  • 19,619
  • 32
  • 105
  • 171
  • 2
    ReadOnlyCollection has a constructor, if I remember correctly, that'll take your List. `return new ReadOnlyCollection(_previousGuesses);` Try recompiling and see if your other error goes away. – GGulati Feb 11 '12 at 22:49
  • you need to initialise the collection before attempting to access it from a method call, a Getter is simply a method call. – Lloyd Feb 11 '12 at 23:55

1 Answers1

7

I guess the favor is not to post the first thing that pops up on google but how about this?

   return _previousGuesses.AsReadOnly();

From here

Orkun
  • 6,998
  • 8
  • 56
  • 103
  • i thought the first problem was related to the 2nd one. @JasonCraig could you elaborate on the 2nd one (if u sill have it / remember) ? – Orkun Feb 22 '12 at 17:47