473,594 Members | 2,812 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Dicti onary<string, string= new Dictionary<stri ng, 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 1888
Andy B <a_*****@sbcglo bal.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.Dicti onary<string, string= new Dictionary<stri ng, 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.Dicti onary<string,st ringcould be a
nested type) but then there's no variable declaration.

Did you mean

Instance.Dictio nary = new Dictionary<stri ng,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.co m>
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_*****@sbcglo bal.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.Dicti onary<string, string= new Dictionary<stri ng, 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.Dict ionary<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.Collecti ons;

using System.Configur ation;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Secu rity;

using System.Web.UI;

using System.Web.UI.W ebControls;

using System.Web.UI.W ebControls.WebP arts;

using System.Web.UI.H tmlControls;

using System.Xml.Linq ;

using ContractService Provider.Contra ctModel;

namespace Main.Admin.Cont racts.Stock {

public partial class Add : System.Web.UI.P age {

protected void Page_Load(objec t sender, EventArgs e) {

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

Contract Contract = new Contract();

Contract.Dictio nary = new ContractDiction ary<string, string>();

Contract.Sectio ns = new ContractSection s<string, string>();

}

protected void AddStockContrac tWizard_ActiveS tepChanged1(obj ect sender,
EventArgs e) {

AddStockContrac tWizard.HeaderT ext = AddStockContrac tWizard.ActiveS tep.Title;

}

protected void AddDefinitionBu tton_Click(obje ct 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.Dictio nary.Add(WordTe xtBox.Text, DefinitionTextB ox.Text);

ListItem ListItem = new ListItem();

ListItem.Text=W ordTextBox.Text +": "+DefinitionTex tBox.Text;;

ListItem.Value= WordTextBox.Tex t;

DefinitionList. Items.Add(ListI tem);

}

}

}
The line where it says: Contract.Dictio nary<string, string= new
ContractDiction ary<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*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Mon, 21 Apr 2008 12:25:18 -0700, Andy B <a_*****@sbcglo bal.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.Dicti onary<string, string= new Dictionary<stri ng, 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.Dict ionary<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_*****@sbcglo bal.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.P age
{
Contract Contract = new Contract();

protected void Page_Load(objec t sender, EventArgs e)
{
Contract.Dictio nary = new ContractDiction ary<string, string>();
Contract.Sectio ns = new ContractSection s<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.Dictio nary<string, string= new
ContractDiction ary<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.Cont racts.Stock {
public partial class Add : System.Web.UI.P age {

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

Contract.Dictio nary = new ContractDiction ary<string, string>();

Contract.Sectio ns = new ContractSection s<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.Dicti onary" 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
6941
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 guess I'll try to narrow it down to a few specific questions, but any further input offered on the subject is greatly appreciated: 1. Are all of my class's methods supposed to take 'self' as their first arg? 2. Am I then supposed to call...
6
22505
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 instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was 'myDog' without having to pass it as a parameter. //////////////////////////////// function...
12
8684
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 update after making changes, but I don't want that update button. How can I get the updated object when the user presses one of my other action buttons?
3
1493
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 such a customized dictionary thingie an instance dictionary, and get some custom namespace behavior out of that. ... __: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465748 ... __: http://aspn.activestate.com/
5
2111
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 it finds a matching "Broom", i want it to return a "Broom" object to the calling program. I want the static method to call the constructor for the "Broom" class. I want this static method, (and one other called "CreateBroom") to be the only...
5
2213
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 implementations vary slightly and I wanted to post the question to the .Net community to get some feedback. So here is the issue: When designing classes both the senior developer and I agree that data access should be abstracted out from a business object...
12
2553
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 about it. I wanted that on my class delete should not work. Object pointer should be deleted using my function only which is taking care of reference count for particular class. Thanx in advance for your inputs.
7
1298
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 instance?
11
6236
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 the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this?
0
7946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8253
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8009
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8240
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6661
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5411
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3867
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1482
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.