decrypt Posted September 10, 2006 Posted September 10, 2006 This should hopefully be an easy question to answer. Basically what I want to know how to do, is how to create an object that can be accessed in any class in the project without having to actually pass it into every single class. At the moment I'm creating the object in the main form and then passing that object into a class' constructer. When I have one thing that keeps getting passed into a bunch of classes it starts to get confusing. Is there something like an include file in c#.net so that I could just define it in there and use it throughout the project? Is there an easier way to do this? Quote
Administrators PlausiblyDamp Posted September 10, 2006 Administrators Posted September 10, 2006 You could declare the methods / properties as static ( C# 2.0 the class itself could be declared static) - this would result in only a single instance being allocated in memory. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
decrypt Posted September 11, 2006 Author Posted September 11, 2006 But how could I access that object from anywhere in the project once it's created? Would making the object static allow me to do this? Say I create a string in the main form and I have about 5 classes in the project. How could I make it so that that string could be accessed from anywhere in the project without having to pass it or it's parent into all of the classes? Is there a way to sort of do something like this: Form 1: global string gHello; gHello = "test"; Class 1: MessageBox.Show(gHello); //outputs test I'm trying to ask this as simply as possible using a string. I guess I'm sort of going away from object-oriented programming. I could live without the luxury of being able to do this if it's not possible. It's just it would make things a lot easier if it is. Quote
*Experts* mutant Posted September 11, 2006 *Experts* Posted September 11, 2006 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfstaticpg.asp Quote
Administrators PlausiblyDamp Posted September 11, 2006 Administrators Posted September 11, 2006 It might be better to rethink your approach, if the string is part of the form then why would the other classes need access to it? It might help if you gave a little more detail about why you need this as there may be an alternate solution. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
decrypt Posted September 11, 2006 Author Posted September 11, 2006 Thanks for the link, I finally understand how statics work and it's just what I was looking for :P Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.