You need to declare class DB
as internal class DB
or public class DB
.
Inconsistent accessibility on class [duplicate]
-
03-06-2022 - |
Pregunta
I am getting the following error
Error Inconsistent accessibility: field type 'Project3_MineSweeper.DB' is less accessible than field 'Project3_MineSweeper.Form2.db'
Here is the code in DB.cs
class DB
{
private string connectionString;
public string ConnectionString
{
get { return connectionString; }
}
private SqlConnection connection;
public SqlConnection Connection
{
get { return connection; }
}
public DB()
{
connectionString="Data Source=NGFAJAR-PC\\FAJAR;Initial Catalog=DB;Integrated Security=True";
connection = new SqlConnection(connectionString);
}
}
And this is the code of Form2.cs
public partial class Form2 : Form
{
public DB db; //it's here where I am getting the error
private Form3 form3;
public Form2()
{
db = new DB();
InitializeComponent();
}
...
}
Lastly, Form3.cs
public partial class Form3 : Form
{
private Form2 form2;
public Form3()
{
InitializeComponent();
}
public void loadData()
{
DataTable dt = form2.db.GetData();
dgvScore.DataSource = dt;
}
}
What's wrong? And what should I do to fix it? Thanks for your appreciated attention and help.
Solución
Otros consejos
What's wrong?
The type DB
is declared as class DB
with no explicit access modifier. This is probably good. Then the default accessibility for a direct member of a namespace (Project3_MineSweeper
), is internal
. So DB
is an internal
class.
Now Form2
is a public
class. Public means that anyone, even code outside this "program" (this assembly) can see Form2
. Now Form2
has a field db
which is also public
. So db
is public inside a public class, so db
can be seen from the outside. But here's the problem: People outside your program don't even know there's a type called Project3_MineSweeper.DB
. So how can they see a field of a "secret" type? Here's the inconsistency.
And what should I do to fix it?
Make the accessibilities compatible, for example be changing the field to internal
, so:
public partial class Form2 : Form
{
internal DB db;
...
}
Change you DB class like so
public class DB
{
....
}