So I am fairly new to C# (not programming in general) and I wrote some code with nearly Zero error handling to make a proof of concept for running in VS only. Now I am getting ready to build some error handling into the application so that the application can be deployed. So now I am having issues figuring out how/where to declare variables so that I can properly configure a Try Catch block.
So with primitive types I just create the variable outside of the block
Before:
String TheString = "Some times I break";
SomeFunctionThatBreaks(TheString);
SomeFunctionThatDoesntBreak(TheString);
After:
String TheString ="";
Try
{
TheString="Some Times I break";
SomeFunctionThatBreaks(TheString);
}
Catch
{
MessageBox.Show("Error")
return false;
}
SomeFunctionThatDoesntBreak(TheString);
However with complex types such as FileStream I am not sure of the proper way to create a EMPTY variable for later use:
Before:
FileStream SourceFile = File.OpenRead(TheFile);
StreamReader sr ; = new StreamReader(SourceFile);
char[] block = new char[3];
byte[] header = new byte[6];
SourceFile.Read(header, 0, 6);
SourceFile.Seek(0, 0);
encoding = (header[1] == 0 && header[3] == 0 && header[5] == 0) ? Encoding.Unicode : Encoding.UTF8;
sr.ReadBlock(block, 0, 3);
String sBlock = new String(block);
SourceFile.Seek(0, 0);
if(sBlock=="ABC")
{
MyFunction(SourceFile);
}
Causes compile errors:
FileStream SourceFile ;
String sBlock ="";
Encoding encoding;
StreamReader sr;
try
{
SourceFile = File.OpenRead(TheFile);
sr = new StreamReader(SourceFile);
char[] block = new char[3];
byte[] header = new byte[6];
SourceFile.Read(header, 0, 6);
SourceFile.Seek(0, 0);
encoding = (header[1] == 0 && header[3] == 0 && header[5] == 0) ? Encoding.Unicode : Encoding.UTF8;
sr.ReadBlock(block, 0, 3);
sBlock = new String(block);
SourceFile.Seek(0, 0);
}
catch (Exception ex)
{
String Error = "Error Accessing: " + TheFile + " System Message: " + ex.Message;
EventLog.LogEvent(dtmLogging.LogEventType.Error, Error);
MessageError(Error, "MyFunction()");
}
if(sBlock=="ABC")
{
MyFunction(SourceFile); //THIS LINE DOES NOT COMPILE: Use of unassigned variables
}
Proposed Change: //If I make this change application appears to work fine, but I am not sure if this is "Proper"
FileStream SourceFile =null;
String sBlock ="";
Encoding encoding = null;
StreamReader sr = null;
Thank you for any help