Missing something fundamental with C# OOP

T

truevision.net

Hi,

I have a slight problem with how things work that I'm sure I'm
missing. I don't really get it how I am supposed to get references
between classes and instances of them. Example:

using System;
using System.Windows.Forms;

namespace Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// Object references

public Database db;


// Methods

public void openToolStripMenuItem_Click(object sender,
EventArgs e)
{
Database db = new Database();
}

private void closeToolStripMenuItem_Click(object sender,
EventArgs e)
{
db.SaveAs();

}
}
}

I have a seperate class that I call Database.

In the above example I select the "open" menu on the form and I
instantiate the db (Database) class. After that I select the "close"
on the form to save the file but here I get the error that "Object
reference not set to an instance of an object.".

I thought I did that in the openToolStripMenuItem_Click method. I was
however forced to set an object reference earlier in the code
though...

What am I missing here?
How can I access the methods of a class in a method that were
instatiated in another method?

Please advice.


/TJ
 
T

thinfox

The reason is openToolStripMenuItem_Click event handler, you're
creating a local instance of your Database class, instead of
instantiating the global variable with the same name "db".

your code should look like this:
public void openToolStripMenuItem_Click(object sender,
EventArgs e)
{
db = new Database();
}

in this case, db actually refers to the global variable not a local
one.
 
P

Peter Duniho

The reason is openToolStripMenuItem_Click event handler, you're
creating a local instance of your Database class, instead of
instantiating the global variable with the same name "db".

your code should look like this:
public void openToolStripMenuItem_Click(object sender,
EventArgs e)
{
db = new Database();
}

in this case, db actually refers to the global variable not a local
one.

Noting, however, that "db" isn't a "global variable", it's an "instance
field member" (that is, it's a class member that exists in each instance
and is a field, as opposed to a property, method, or type). And noting
also that it's generally not a good idea to have public fields. If you
want the data exposed publicly, it's better to wrap it in a property.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top