Objects variables fields vs Objects in functions
Hello All,
I am new to the development world and have a question. In the following code below, "FileStream fileStream" and "StreamWriter streamWriter;" are both object variables, correct? (if not, what do you call them?)
Why would you declare it as a field as oppose to instatiating the class like "StreamWriter streamWriter = new StreamWriter();" and using it in your functions?
I've seen this before in other places used many times.
What advantages does that give you?
Sample Code
public class FileLogger
{
//what do you call this and why use it this way?
FileStream fileStream;
StreamWriter streamWriter;
public FileLogger(string filename)
{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}
public void Logger(string s)
{
streamWriter.WriteLine(s);
}
}
Jaish MathewsPosted Jun 22, 2010, 6:54 AM
Hi,
A
//what do you call this and why use it this way?
FileStream fileStream;
StreamWriter streamWriter;
We can call them object variables rather than primitive variables i.e. int i
B
We are declaring them like this, as same object variables can use in different location. i.e.
Below I have 2 metods where used same variables. Other wise I need to again write another set of same object varibles for 2nd method too.
FileStream fileStream;
StreamWriter streamWriter;
Private void Method1()
{
fileStream = new FileStream(filename, FileMode.Create)
streamWriter = new StreamWriter(fileStream);
}
Private void Method2()
{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}