Search code examples
c#unity-game-enginepropertiesencapsulation

Why does my private array give me an inconsistent accessibility error using a public property to get it


Thanks for looking and thanks in advance for any advice you may have

I'd like to keep my array 'notes' private, as no other class should be tampering with it.

I do need other classes to read that data though, so thought that creating a property for it would be the correct way to go about encapsulating it.

However I get this error in Unitys console

Assets/testScripts/rhythmGameNotes.cs(22,23): error CS0053: Inconsistent
accessibility: property type `rhythmGameNotes.note[]' is less accessible      
than property `rhythmGameNotes.Notes'

Below is the source code (chopped up a bit)

private struct note
{
    public float y;
    public float noteDuration;
    public float noteSample;
    public GameObject go;
}

private note[] notes; // this should remain hidden from other classes

public note[] Notes
{
    get
    {
        return notes;
    }
}

Thanks again

Jim


Solution

  • The issue that you have is that your note struct is private and therefore only accessible to classes within the same file.

    But as you are wishing to access this from the outside world people do not have access to the note Type meaning that when you are attempting to do:

    public note[] Notes
    {
        get
        {
           return notes;
        }
    }
    

    Your error is saying that the Type note is unable to be resolved publically. If you require people to access this struct from the property you will have to make the struct public:

    public struct note
    {
        public float y;
        public float noteDuration;
        public float noteSample;
        public GameObject go;
    }
    

    One further thing to note is that if you do not want any other class modifying your nice collection of notes then I would recommend that you change your property from returning an array to returning a ReadOnlyCollection<note>.

    public ReadOnlyCollection<note> Notes
    {
        get
        {
            return new ReadOnlyCollection<note>(notes);
        }
    }
    

    The reason for this as it says to classes using your object, this collection is not for modifying and is only for reading. I find this is more descriptive than a standard array and if I were using your class would tell me that there is no reason to make changes to the objects within the collection.