Reputation: 3233
I have a method in c#, in which it return an object! I need to use a try catch here
this is my method
public T FromBinary()
{
T obj;
try
{
using (Stream stream = File.Open(this.serializeFilePath, FileMode.Open))
{
var binaryFormatter = new BinaryFormatter();
obj=(T)binaryFormatter.Deserialize(stream);
}
}
catch (Exception e)
{
EventLog.WriteEntry("Cannot convert Binary to object", e.Message + "Trace" + e.StackTrace);
}
return obj;
}
But i am getting an error
Use of unassigned local variable 'obj'.
How can I use try catch in method having return object T?
Upvotes: 3
Views: 677
Reputation: 2243
you have to write T obj = default(T);
to assign the variable with a initial value
Upvotes: 4
Reputation: 83
The error occurs because you are trying to let your method return the object before it has been assigned a value(if the code throws an exception).
the solution is to set your declaration to:
T obj = Default(T);
You should also make it a try-catch-finally so that you allways return the object and close the file stream like this:
}//end of catch block
finnally{
stream.Close();
return obj;
}
}//end of method
Upvotes: 0