简体   繁体   中英

Able to set value of private variable by public property without setter

How is this code able to compile and run error free?

private void queueToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //Class name MDPlayer
        Playlist.QueueList.Add(tempPlayList[songView.SelectedIndex]);
        Playlist.GetQueue = null;
        QueueCombobox.Items.Clear();
        foreach (PlayListData pld in Playlist.QueueList)
        {
            QueueCombobox.Items.Add(pld.Track);
        }
    }
class Playlist
{
private static List<PlayListData> queueList = new List<PlayListData>();

    public static List<PlayListData> QueueList
    {
        get { return queueList;}
    }
}

How am I able to add to queueList that is private through the public property QueueList that doesn't even have a setter?

You are able to call methods on the return value of a property getter.

Your property getter returns a List<> . List<> defines the Add method. Thus you can call the Add method on the List<> that you asked for.

Note that you can not assign a new value to the listQueue from outside the PlayList class because it is private .
Also, you can not assign a new value to the ListQueue property because it has no setter accessor.
This will fail: PlayList.QueueList = new List<PlayListData>();

Because you're adding to the list via the getter. You're not setting the underlying private variable to anything. You can do QueueList.Add() , but not QueueList = newList .

When you get a value from the getter, it returns the whole class and that class is alterable. You only need a setter when you want to set the whole variable to an entirely different class.

Summary You only need to use a setter when setting the whole variable.

Can

Playlist.QueueList.Add(tempPlayList[songView.SelectedIndex]);

Cannot

Playlist.QueueList = new List<PlayListData>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM