Tech MC

Tech MC

  • NA
  • 1
  • 0

Objects variables fields vs Objects in functions

Jun 21 2010 9:03 PM

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);
        }
     
    }

Answers (1)