Passing Values Between Classes
Ok, I have my main class called UDPListener which inherits from Form
public partial class UDPListener : Form
And in this class, I have a text box I write to named "StatusTextBox"
I have another class named "PortHandler" that I want to perform operations on said text box.
Is there anyway to get StatusTextBox into the PortHandler class without using "get {} set{}" and creating a class object of UDPListener so I can utilize it in the PortHandler class?
I have tried "get {} set{}" but I have to create a new class object of UDPListener and it creates a new form. Thats no good as I want to write the the text box on the existing form.
I have tried using inheritance:
public class PortHandler : UDPListener
But that doesnt work. I think I'm having a brainstorm though and I cant test it out! :cry: If I remember how it goes in C++ (my primary background), when you create a class object, say in UDPListener : Form, you can pass it parameters and the constructor will load those parameters into the class upon instantiation. Hm... I may have just answered my own question...
Any input is still helpful though! :D
# 1 Re: Passing Values Between Classes
yes putting input in the constructor or parsing input using properties or functions after the object have been created is what i mostly do
not of cause that mean there could be no better way
# 2 Re: Passing Values Between Classes
yes putting input in the constructor or parsing input using properties or functions after the object have been created is what i mostly do
Those are the only 3 ways :p
If you're object *needs* the data to work, it really should go in the constructor. After that it's up to you how ya do it.
# 3 Re: Passing Values Between Classes
Those are the only 3 ways :p
If you're object *needs* the data to work, it really should go in the constructor. After that it's up to you how ya do it.
Thats what I thought, I suddenly remembered from C++ thats how you do it and it kicked me in the head, lol. Easy enough, all I can say is... duh! Thanks :wave:
# 4 Re: Passing Values Between Classes
I believe i am having the same problem, im very new to programming and trying to figure out how to pass variables between classes, i thought keyword 'public' would enable that?
//start code
public class class1
{public string x = "hello";
System.Console.WriteLine ("Hello World!"); }
class class2
{ static void Main()
{ System.Console.WriteLine(class1.x);
class1; //trying to execute class1 from within class2 to write "hello world"
} }
//end code
Why doesnt that work? Niether of the 2 lines in class2 build.
I was also wondering how to execute a class within another class eg above trying to execute hte "hello world" by calling "class1;" ive also tried calling it from a method (i think?) within a class eg class1.method, if the writeline command was within a method.
I appologise because i know this is a really stupid question, but that is what has been bugging me. Also obviously it would be easier to put it all in one class, but ive broken down the problem im facing when tryin to do larger things to the simplest explanation. Thanks for any help.
# 5 Re: Passing Values Between Classes
I believe i am having the same problem, im very new to programming and trying to figure out how to pass variables between classes, i thought keyword 'public' would enable that?
public class class1
{
public string x = "hello";
System.Console.WriteLine ("Hello World!");
}
class class2
{
static void Main()
{
System.Console.WriteLine(class1.x);
class1; //trying to execute class1 from within class2 to write "hello world"
}
}
You have several issues. For one this Class1 won't compile because you can't execute a statement within the body of the class. In order for your Console.WriteLine statement to work you need to put it within a method. Rather than declaring a public field you may want to use a property. Within the Main() method, you need to new up an instance of Class1 before you can use it. Here's the fixed up code.
namespace CGTestConsole
{
#region Using Directives
using System;
#endregion Using Directives
class Class1
{
#region Public Properties
public string Text { get { return _text; } }
#endregion Public Properties
#region Public Methods
public void DisplayText( )
{
Console.WriteLine( _text + " using the DisplayText method." );
}
#endregion Public Methods
#region Private Fields
private string _text = "Hello World";
#endregion Private Fields
}
class Program
{
static void Main( string[ ] args )
{
// Declare an instance of class1
Class1 class1 = new Class1( );
// Write to the console using the get property of class1
Console.WriteLine( class1.Text );
// Write to the console using the class method
class1.DisplayText( );
}
}
}
Arjay at 2007-11-9 11:40:13 >

# 6 Re: Passing Values Between Classes
Arjay makes some very good points and they'll make more sense to you as you gain experience. Here's your code, slightly modified to compile and workpublic class class1
{
public string x = "hello";
public void DisplaySomething()
{
System.Console.WriteLine("Hello World!");
}
}
class class2
{
static void Main()
{
System.Console.WriteLine(new class1().x);
new class1().DisplaySomething(); //trying to execute class1 from within class2 to write "hello world"
System.Console.ReadLine();
}
}Hope it helps you understand how classes use each other. . .
# 7 Re: Passing Values Between Classes
You can pass a variable to another class by using the "get {} set {}" method and calling it from the class you need it in.
public partial class Main : Form
{
MyClass My_Class = new MyClass();
string myString;
public void makeString()
{
myString = "Hello!";
My_Class.retrieveString();
}
public String Main_String
{
get { return myString; }
set {myString = value; }
}
}
class MyClass
{
Main getString = new Main();
public void retrieveString()
{
string MainString = getString.Main_String;
}
}
Kind of a useless example but I hope it made a point, lol
# 8 Re: Passing Values Between Classes
Thanks heaps for the replies guys, very helpful. Ill have to read it a few more times i think :) but very helpful.
cheers,
Mick.
# 9 Re: Passing Values Between Classes
You can pass a variable to another class by using the "get {} set {}" method and calling it from the class you need it in.
public partial class Main : Form
{
MyClass My_Class = new MyClass();
string myString;
public void makeString()
{
myString = "Hello!";
My_Class.retrieveString();
}
public String Main_String
{
get { return myString; }
set {myString = value; }
}
}
class MyClass
{
Main getString = new Main();
public void retrieveString()
{
string MainString = getString.Main_String;
}
}
Kind of a useless example but I hope it made a point, lol
That wouldn't work at all. "MyClass" creates a "Main" object that has nothing to do with the "Main" object that you're working from.
If you wanted to do it like that you'd have to transfer the "Main" object through MyClass' constructor as a parameter.
But I wouldn't suggest doing things like that at all, if it could be avoided. It makes it a lot harder to maintain. The less classes contain instances of eachother, the better.
# 10 Re: Passing Values Between Classes
That wouldn't work at all. "MyClass" creates a "Main" object that has nothing to do with the "Main" object that you're working from.
I actually used get {} set {} on a new object of my GateMaster class and grabbed a COMPort value from another class and it worked just fine. Though... I will try your method however, it sounds more reasonable than creating a "new" class object when one is already in existence.
The only thing is, when the class your passing goes out of scope, wont the automatic destructor (A.K.A. Garbage Collector) clean it up?
Or does the fact that it inherits from "Form" keep the GC from destroying it because Form is always there so long as the program is running?
# 11 Re: Passing Values Between Classes
I actually used get {} set {} on a new object of my GateMaster class and grabbed a COMPort value from another class and it worked just fine. Though... I will try your method however, it sounds more reasonable than creating a "new" class object when one is already in existence.
The only thing is, when the class your passing goes out of scope, wont the automatic destructor (A.K.A. Garbage Collector) clean it up?
Or does the fact that it inherits from "Form" keep the GC from destroying it because Form is always there so long as the program is running?
Erh, my reply was mainly to your example which wouldn't work (though it would appear to work, because the string you were getting was static). View example below.
And the garbage collector won't destroy it as long as there's something pointing to it somewhere in the program.
Example:
public partial class Main : Form
{
private TextBox t1; // First textbox, will extract text from here
private TextBox t2; // Second textbox, will place whatever's gotten from MyClass her
private Button b1; // Click will start simulation
public Main()
{
InitializeComponent();
// Usually done by designer in VS2005
t1 = new TextBox();
t1.Location = new Point(10, 10);
t2 = new TextBox();
t2.Location = new Point(10, 35);
b1 = new Button();
b1.Location = new Point(10, 60);
b1.Text = "Simulate";
b1.Click += new EventHandler(b1_Click);
Controls.Add(t1);
Controls.Add(t2);
Controls.Add(b1);
}
void b1_Click(object sender, EventArgs e)
{
MyClass myClass = new MyClass();
t2.Text = myClass.retrieveString();
}
public string Main_String
{
get { return t1.Text; }
set { t1.Text = value; }
}
}
public class MyClass
{
Main getString = new Main();
public string retrieveString()
{
return getString.Main_String;
}
}
Another thing in your code you should be careful about is that in your "Main" you create a new instance of MyClass, which creates a new instance of Main, which creates a new instance of MyClass, until you get a stack overflow.
# 12 Re: Passing Values Between Classes
You can pass a variable to another class by using the "get {} set {}" method and calling it from the class you need it in.
public partial class Main : Form
{
MyClass My_Class = new MyClass();
string myString;
public void makeString()
{
myString = "Hello!";
My_Class.retrieveString();
}
public String Main_String
{
get { return myString; }
set {myString = value; }
}
}
class MyClass
{
Main getString = new Main();
public void retrieveString()
{
string MainString = getString.Main_String;
}
}
Kind of a useless example but I hope it made a point, lolDont post useless examples !! Your example is very confusing for new people in C# it rather confuses them instead of to help. Why ?
1) Never use Keywords like Main in another meaning as it is used in standard MS way. This confuses people
2) Never use wordcombinations which normally would be used for methds for fields. Like you used getString This suggests a method to get a String from another class. This are rules which arn't really written down anywhere because we know C# is case sensitive and this way the compiler may work even in your case. But it confuses new people.
So this I'm telling you because of my 20 year experience of how to teach my trainees in our firm. The rule in programming simple says Use descriptive names. And getString is descriptive but descriptive, suggesting wrong ideas. Naming an object of class 'Main' with getString.
I havn't tested your project, but are you sure it doesn't deadlock ?
Creating MyClass will Create inside a class Main object --
Creating class main in itself creates a new class Myclass object-
and this again creates a class Main --and so on until memory is finished !!:lol: :lol: I'm sure this troubles
# 13 Re: Passing Values Between Classes
And to add another to the list:
3) Never post code without running it under the debugger. Try out your code first before posting it.
Arjay at 2007-11-9 11:48:13 >

# 14 Re: Passing Values Between Classes
And to add another to the list:
3) Never post code without running it under the debugger. Try out your code first before posting it.Yea :D this is a point which should be a standard rule for all people who like to be helpers here in forum. If you havn't tested code before posting it, dont post it.
# 15 Re: Passing Values Between Classes
I named it getString because thats kinda what it does in theory, it "gets" the string from the Main class. But this code is kind of obsolete now, lol. I used code similar to it in my TCP/IP chat project but Ive since revised it considerably by using programmer defined constructors and the like.
It was just a simple example and I couldn't think of anything to name my variables in this one so I just tried to make them as generic as possible. Though I guess my naming conventions are STILL evolving. But I have a question. Is Hungarian notation a good idea? I can take it or leave it, but I want to know if its good practice to use it or not? Ive heard arguments from both sides...
I can see the benefits in it, what with being able to tell what the datatype is just by looking at the first 3 or 4 letters, but I can see the downside as well in that it can be kind of confusing in that when you get into different classes and the like, such as SerialPort and NetworkStream, that it might be a bother and its just easier to name them something like "TCPNetStream" or something like that.
EDIT: I usually make up "quick" names for variables while in development because I don't want to spend a lot of time trying to think up descriptive names for variables. That and I'm more worried about just getting the program to work. Later on when everything is humming along Ill take the time and go in and change the names. VS helps a TON with this seeing as how when you change the name of a variable at the declaration it often times changes it throughout the entire assembly which is awesome and makes things go much faster. Though I really should do it while writing the initial code, but then I often end up changing the stuff later on when I decide that something else might work better, I think of a better name, I change some code somewhere and the name is no longer descriptive, etc... Ive only been programming for about a month in "the real world" so I still have a lot to learn about coding etiquette, I'm sure. But these things come with time and experience :)
# 16 Re: Passing Values Between Classes
In generaly you want to avoid using names that key off the datatype.
Things like MyMap, GetString etc. aren't descriptive enough because when you look at it, all things can be decomposed into the fundemental data types so if you named everything that way it would be hard to follow.
With regard to the Main. Since you are deriving from form, may I suggest using 'MainForm' to indicate that this is the main form of the application. When you create an instance of this class don't declare it as (not that you typically need to declare it but that's another conversation):
Main getString = new Main();
but rather
MainForm mainForm = new MainForm();
As far as hungarian notation, for C++ it's okay. Even Hungarian is dated now in C++. Consider lpszSomeStr which translates to long pointer to a [null terminated] string. Long pointer is a hold over from Win16 days and it doesn't mean anything in Win32.
In C#, it's doubly dated. For me it felt odd not using a simplified version of Hungarian when I moved to C#, but C# is more type safe than C/C++ was and the compiler will generally catch invalid casts (unlike casting a void in C) so the benefits of using Hungarian to visually help catch these types of errors is no longer required.
Whatever naming convention you pick (or have to follow in your organization), just stick to it and be consistent.
I'd suggest following the C# style when coding in C# (because when in Rome...). This will make your code easier to read when other folks take over the code. If your C# code looks like it's been written by a C programmer, it's going to be harder to understand when read by a C# programmer (especially one without a C background).
Arjay at 2007-11-9 11:51:17 >

# 17 Re: Passing Values Between Classes
I named it getString because thats kinda what it does in theory, it "gets" the string from the Main class.
Please reread basic books you have some big misunderstoods here. No it doesn't get a string it is the placeholder for an object so it should have a name which makes understandable that this is an object.
Also Main is a wrong name because this isn't what Main suggests to be
Maybe for your 'Main' class a better name would have been TestFormClass or something like that.
It was just a simple example and I couldn't think of anything to name my variables in this one so I just tried to make them as generic as possible.
Please also clear up what 'generic' means. I couldn't find anything 'generic' in this example.
But I have a question. Is Hungarian notation a good idea? I can take it or leave it, but I want to know if its good practice to use it or not? Ive heard arguments from both sides...
It is as you just say. Arguments for both sides.
In some cases I'm personally using it e.g I name TextBoxes with txt in the firstplce followed by the need of the Box e.g. txtFamilyName or btClose for a closing button. But I dont name all Fields which are integers beginning with an 'i' because the compiler is good enough to check that you are just rying to add an integer to a string or other errors which occur. But this is a bit of private customs and as I have seen granted from other programmers with respect. But giving significant names could be done wrong in different ways. Basically: A Field holds something ( a value, a date, an object ) but it is never doing something . Because of this names using get, let , set ... as prefixes for Fields are not a good idea. Get it.
Animal dog = new Animal(); // good
Animal findACat = new Animal() // very bad
Get the idea of an object. A class is an object. In the above example dog is the place where an object Animal() will be created. It is the adress where you may adress it. And because you have the adress of your Animal class now you can get your Object doing something like
dog.FindBone();
dog.Shout("wauuuu ");
The other error to give significantnames is to overdo it like
string stringMyBigListViewsFirstColumnsHeaderTitleString = "Name"
:lol: You are loughing now. ? I have seen such things already
:lol:
Try to do descriptive names as best as you can, especially for classes but also for variables ( Fileds) because after I while you havn't read your code you would never again find out why in the world you have had
if( d != null && d.Name == stxt ){
for(int l= 0; l < el; l++){
for (int c = 0 c < cm;c++){
...
}
}
}
Do you know whats going on here ? Noooo If you create it you will know whats going on, but half a year later ?
If instead of this you may have
If( document != null && document.Name == docName ){
for (int line = 0; line < endline; line++){
for ( int col = 0; col < colMax; col++){
........
}
}
}
Simple get the idea any you will know how to do.
But these things come with time and experience :) I agree.
# 18 Re: Passing Values Between Classes
Noone sits down and says to themselves "****, i need to think of a descriptive name for my variable... better go look up the dictionary".
Good names aren't hard. Name them for their purpose. For example if you were looking at MP3 metadata and you saw variables like:
ar
tt
al
tn
Could you figure those out easily? How about:
Artist
TrackTitle
Album
TrackNumber
Those are easy ;)
# 19 Re: Passing Values Between Classes
ar
tt
al
tnI was thinking these were states. Here's what I have so far:
AR - Arkansas
TT - Um?
AL - Alabama
TN - Tennessee
Arjay at 2007-11-9 11:54:19 >

# 20 Re: Passing Values Between Classes
I had a Visual Basic instructor that was OBSESSED with Hungarian notation. If you didn't use it, you lost 5 points per (mis?)use. So I got used to it, then I got pulled into another direction when using C# and I guess I'm at the mid point where my naming conventions are kind of evolving from utilizing that notation method. I realize naming conventions are very important, just gotta settle on a certain kind and then use it consistently. So basically if I declare a class object for say... my "main" class and its name is UDPListenerMain : Form, then I should write:
UDPListenerMain udpListenerMain = new UDPListenerMain();
And that would let me or someone else know that the object I just created is an object of the UDPListenerMain class. What I would originally do is create a class object as such:
UDPListenerMain GetCOMPort = new UDPListenerMain();
And I see now just how that doesn't make sense. If someone were to see that way down the line, they'd look at it and say "huh?" Because it looks as though it has nothing to do with the class its encapsulating. My whole idea was that naming it something like that would let the person know what it was for, but I see now that if I named it that, and then had to use that class object for something else, it wouldn't make sense at all. So naming the object after the class it encapsulates is the best route to take :)
I didn't realize naming conventions could be such a big topic! :wave: But I'm just now starting to get into thinking ahead, and thinking about how to write code that not only works, but is meaningful and maintainable in the future. Thanks for all the help you guys, i will go home and do some fine tuning on my naming conventions after work, lol!
# 21 Re: Passing Values Between Classes
I was thinking these were states. Here's what I have so far:
AR - Arkansas
TT - Um?
AL - Alabama
TN - Tennessee:D :D :lol: :lol: :lol: :thumb: lol-rofl --