I’m having some trouble understanding access modifiers; I want to know better when to use what level of access, especially for properties–just links to good tutorials on that subject could be its own question.
But more specifically, I don’t understand why an object bound to a WinForm control has to be public. So I create my object:
public class Foos : List<Foo>
{
}
public class Foo
{
private int bar;
public int Bar
{
get { return bar; }
set { bar = value; }
}
}
then bind it to a DataGridView
public partial class Form1 : Form
{
private Foos formFoos;
public Form1()
{
InitializeComponent();
formFoos = new Foos();
AddFoo();
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = formFoos;
}
/// <summary>
/// generate some test values
/// </summary>
private void AddFoo()
{
for (int i = 1; i <= 5; i++)
{
Foo foo = new Foo();
foo.Bar = 5 * i;
formFoos.Add(foo);
}
}
}
Works fine. But what if I don’t want to expose Foo.Bar outside my assembly? If I make it internal int Bar I get an empty dataGridView1. If I make it protected I get a compiler error, because of course Form1 is not derived from Foo.
How does a control in a form in my program not match the definition of internal though?
Internal members are accessible only within files in the same
assembly.
General wisdom on how you make these declarations in a systematic way also welcomed.
You should mark the whole
Fooclass asinternal.This way, the entire
Fooclass and all it’s members will be invisible outside the assembly.Form1.dataGridView1needsFoo.Barto be public, otherwise it won’t be able to make use of it.Now, because
Foois already markedinternal, it can exposeBaraspublicwith no risk of exposing it outside the assembly.This should make both
Form1.dataGridView1and you equally happy.Fooasinternal,Foosshould also change frompublictointernalbecauseFoosmay not have a higher access level than the class it’s derived from.