473,287 Members | 1,643 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Making an instance of an object available for all events and methods of a class

I am trying to figure out how to make an object instance available for all
methods of a class. I tried to do something like this:

public class test {
TheObject Instance = new TheObject();
TheObject.Dictionary<string, string= new Dictionary<string, string>();
....
}

The first line (TheObject instance = new TheObject();) doesn't get
complained about by the compiler. The next line after it for some reason
doesn't work. I cant get intelisense out of vs2008 for the object if it
isn't inside a method for some reason. Any idea why this is?

Jun 27 '08 #1
5 1871
Andy B <a_*****@sbcglobal.netwrote:
I am trying to figure out how to make an object instance available for all
methods of a class. I tried to do something like this:

public class test {
TheObject Instance = new TheObject();
TheObject.Dictionary<string, string= new Dictionary<string, string>();
...
}

The first line (TheObject instance = new TheObject();) doesn't get
complained about by the compiler. The next line after it for some reason
doesn't work. I cant get intelisense out of vs2008 for the object if it
isn't inside a method for some reason. Any idea why this is?
What is the second line meant to be doing? It looks sort of like a
declaration (in that TheObject.Dictionary<string,stringcould be a
nested type) but then there's no variable declaration.

Did you mean

Instance.Dictionary = new Dictionary<string,string>?

If so, that's a statement which should be in a method - such as a
constructor for your test class.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jun 27 '08 #2
On Mon, 21 Apr 2008 12:25:18 -0700, Andy B <a_*****@sbcglobal.netwrote:
I am trying to figure out how to make an object instance available for
all
methods of a class. I tried to do something like this:

public class test {
TheObject Instance = new TheObject();
TheObject.Dictionary<string, string= new Dictionary<string, string>();
...
}
That code sample doesn't show a single method.
The first line (TheObject instance = new TheObject();) doesn't get
complained about by the compiler.
Well, it is a legal line after all. :)
The next line after it for some reason doesn't work.
I wouldn't expect it to.

"TheObject" is a class name. Even if one assumes that
"TheObject.Dictionary<string, string>" could be a valid l-value expression
(and I don't think it can be...you can't have a generic property or
field), you can't put assignment statements like that in a class
declaration. You can only declare things in a class declaration. If you
want an executable statement, it needs to be inside an executable element,
such as a constructor, method, property setter or getter, etc.

For what it's worth, the subject of your thread here doesn't make much
sense either. An "event" isn't something that would have access to
anything. Nor does the subject seem to have anything to do with the code
you posted, due to the lack of an actual example of a method that might
use this hypothetical instance.

Based solely on your subject, it seems _possible_ that you are trying to
add a static field to a class, so that the field can be accessed by
members of the class. But that's pure speculation. There's really not
enough in your post for me to know for sure that's what you're trying to
do.

In other words, you should really try to figure out how to state your
question in a more clear, less ambiguous way.

Pete
Jun 27 '08 #3
Well, I would imagine that the subject of the post would have everything to
do with the question I posted. The original question was: How do you get an
instance of an object to be useable/available for all methods/events of a
class? I tried putting what I needed to use of the object inside the class
directly, but vs was somehow complaining about it and not saying why... I
can post a full example here, but for "what it's worth..." I posted a full
code sample up here once before and basically got told not to post so much
code all at once because "nobody would read it anyways". Either way, here is
the problem. I need to make this object available to all events/methods of
the code behind of an asp.net page. Since code behinde pages (as far as I
know of, can't have constructers - only a page_load event. I tried putting
the object creation in there, but a particular method couldn't "access" the
code it needed to. Here is the code with comments as it is now.

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Xml.Linq;

using ContractServiceProvider.ContractModel;

namespace Main.Admin.Contracts.Stock {

public partial class Add : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {

//the following objects aren't accessible anywhere else except in here...

Contract Contract = new Contract();

Contract.Dictionary = new ContractDictionary<string, string>();

Contract.Sections = new ContractSections<string, string>();

}

protected void AddStockContractWizard_ActiveStepChanged1(object sender,
EventArgs e) {

AddStockContractWizard.HeaderText = AddStockContractWizard.ActiveStep.Title;

}

protected void AddDefinitionButton_Click(object sender, EventArgs e) {

//the following code is broken because vs complains. it says that a
reference to "contract" is needed. How do you do that?

Contract.Dictionary.Add(WordTextBox.Text, DefinitionTextBox.Text);

ListItem ListItem = new ListItem();

ListItem.Text=WordTextBox.Text+": "+DefinitionTextBox.Text;;

ListItem.Value=WordTextBox.Text;

DefinitionList.Items.Add(ListItem);

}

}

}
The line where it says: Contract.Dictionary<string, string= new
ContractDictionary<string, string>();

Is a nested type inside another type contained inside a public property. It
does actually work because I ran it through a test project before using it
inside the real code. Any ideas how to fix this "references to an object
needed" problem?

Sorry for the sounding of being cranky but it is a long day today...
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Mon, 21 Apr 2008 12:25:18 -0700, Andy B <a_*****@sbcglobal.netwrote:
I am trying to figure out how to make an object instance available for
all
methods of a class. I tried to do something like this:

public class test {
TheObject Instance = new TheObject();
TheObject.Dictionary<string, string= new Dictionary<string, string>();
...
}
That code sample doesn't show a single method.
The first line (TheObject instance = new TheObject();) doesn't get
complained about by the compiler.
Well, it is a legal line after all. :)
The next line after it for some reason doesn't work.
I wouldn't expect it to.

"TheObject" is a class name. Even if one assumes that
"TheObject.Dictionary<string, string>" could be a valid l-value expression
(and I don't think it can be...you can't have a generic property or
field), you can't put assignment statements like that in a class
declaration. You can only declare things in a class declaration. If you
want an executable statement, it needs to be inside an executable element,
such as a constructor, method, property setter or getter, etc.

For what it's worth, the subject of your thread here doesn't make much
sense either. An "event" isn't something that would have access to
anything. Nor does the subject seem to have anything to do with the code
you posted, due to the lack of an actual example of a method that might
use this hypothetical instance.

Based solely on your subject, it seems _possible_ that you are trying to
add a static field to a class, so that the field can be accessed by
members of the class. But that's pure speculation. There's really not
enough in your post for me to know for sure that's what you're trying to
do.

In other words, you should really try to figure out how to state your
question in a more clear, less ambiguous way.

Pete
Jun 27 '08 #4
On Mon, 21 Apr 2008 14:08:02 -0700, Andy B <a_*****@sbcglobal.netwrote:
Well, I would imagine that the subject of the post would have everything
to
do with the question I posted.
Believe me, I do understand that that's what you would imagine. I'm
simply trying to help explain why what you imagine doesn't turn out to be
true.
The original question was: How do you get an
instance of an object to be useable/available for all methods/events of a
class?
That's very similar to the subject, and has the same problem: it doesn't
have a clear connection to the code you posted, and there's no such thing
as an event getting an instance of anything. An event isn't executable
code, it's a member of a class. There can be executable code associated
with the event, but by default that code isn't necessarily going to even
be in the class where the event is defined.

Perhaps you meant "event handler", but an "event handler" is just a
method, so writing "all event handlers and methods of a class" would be
redundant.

We're programmers. It's very important to communicate precisely, because
we work in an environment where different terms that are very similar have
very different meanings.
I tried putting what I needed to use of the object inside the class
directly,
Did you? I didn't see that in any of the code you posted.
but vs was somehow complaining about it and not saying why... I
can post a full example here, but for "what it's worth..." I posted a
full
code sample up here once before and basically got told not to post so
much
code all at once because "nobody would read it anyways".
Well, it's true...there's a difference between "full" and "complete".
Generally speaking, we're _not_ going to want a "full" code sample. That
implies that you've posted every line of code of your executable. But we
do need to see a "complete" sample. That is, one that can be compiled and
executed without adding anything.

"Full" code posts are in fact often ignored, whereas "complete" code
samples are very useful.
Either way, here is
the problem. I need to make this object available to all events/methods
of
the code behind of an asp.net page.
There is a newsgroup specifically for ASP.NET issues. So one point I'll
make is that you may or may not receive the best advice here.

That said...
Since code behinde pages (as far as I
know of, can't have constructers - only a page_load event. I tried
putting
the object creation in there, but a particular method couldn't "access"
the
code it needed to.
I don't know anything about the constructors issue in ASP.NET (see? in a
different, more appropriate newsgroup, you wouldn't be dealing with such
an uneducated person :) ), but assuming you can still have instance
members in your class, then the issue isn't so much about where to
initialize the data (you've already figured that out), but where to put
the data that's been initialized.

In the code you posted most recently, you've got a local variable that you
initialize. Of course, that variable isn't going to be around when the
Load event handler method in which it's contained returns. You need to
put that data somewhere else. That "somewhere else" would be an instance
field.

For example (using your code as a template):

public partial class Add : System.Web.UI.Page
{
Contract Contract = new Contract();

protected void Page_Load(object sender, EventArgs e)
{
Contract.Dictionary = new ContractDictionary<string, string>();
Contract.Sections = new ContractSections<string, string>();
}
}

Theh the remaining code should work okay (ignoring for the moment the
questionable practice of naming fields as if they were properties, and of
initializing your Contract instance in the Page_Load() method rather than
in the Contract class's own initialization code).

This assumes that in ASP.NET code you can have instance fields. Again,
since I don't know anything specific about ASP.NET, I can't tell you
whether that's a true assumption or not. If it's not, then you _really_
need to post your question in a newsgroup specifically about ASP.NET.
[...]
The line where it says: Contract.Dictionary<string, string= new
ContractDictionary<string, string>();

Is a nested type inside another type contained inside a public property.
Are you now referring to your first post in this thread? I didn't see a
line like that in your most recent code.
It
does actually work because I ran it through a test project before using
it
inside the real code.
I don't think so. You can't assign something to a type. It may be a moot
point, but if you think it's important, you should post an example of that
line in code where it successfully compiles.
Any ideas how to fix this "references to an object
needed" problem?

Sorry for the sounding of being cranky but it is a long day today...
I'm sorry it's a long day. I'm sorry if you feel cranky. Just keep in
mind that none of the rest of us are (necessarily) cranky, and you
shouldn't interpret our responses as though we are. :)

Pete
Jun 27 '08 #5
Andy B pretended :
Here is the code with comments as it is now.
[snip]
>
namespace Main.Admin.Contracts.Stock {
public partial class Add : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) {
//the following objects aren't accessible anywhere else except in here...
Contract Contract = new Contract();

Contract.Dictionary = new ContractDictionary<string, string>();

Contract.Sections = new ContractSections<string, string>();

}
Two possible problems here:
1) as Peter pointed out, the variable you declare here is local to this
method. You will need to declare it at class-level to make it visible
"elsewhere".
2) your variable has the same name as it's type. So it's not clear to
me (and how would it then be clear to the compiler) whether
"Contract.Dictionary" is some static property in the Contract *Type* or
an instance property of your local Contract *variable*. If you rename
that variable to "contract" (starting with a lowercase 'c'), that
problem disappears.

Hans Kesting
Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: John M. Gabriele | last post by:
I've done some C++ and Java in the past, and have recently learned a fair amount of Python. One thing I still really don't get though is the difference between class methods and instance methods. I...
6
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object...
12
by: Jim Hammond | last post by:
I am passing the whole object instead or parameters in my select and update methods. I can get the updated object if I set UpdateMethod, let ASP.NET autogenerate an update button, and then press...
3
by: wolfgang.lipp | last post by:
some time after posting my `Linkdict recipe`__ to aspn__ -- basically, a dictionary with run-time delegational lookup, but this is not important here -- i thought gee that would be fun to make...
5
by: ffrugone | last post by:
My scenario involves two classes and a database. I have the classes "Broom" and "Closet". I want to use a static method from the "Closet" class to search the database for a matching "Broom". If...
5
by: Dinsdale | last post by:
I was discussing class architecture with one of the senior developers at my new job and him and I have a similar idea on how to work with data access and class libraries. That said, our...
12
by: Premal | last post by:
Hi, I tried to make delete operator private for my class. Strangely it is giving me error if I compile that code in VC++.NET. But it compiles successfully on VC++6.o. Can anybody give me inputs...
7
by: Andy B | last post by:
I have an instance of an object that needs to be accessed by all members of a page like page_load, button_click events and so on. Where in the codebehind would I put the creation of the object...
11
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.