3

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?

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
S M
  • 3,133
  • 5
  • 30
  • 59
  • 1
    You can assign null to obj initially like `T obj = null;` – yogi Apr 05 '16 at 07:19
  • @yogi.. Soryy now geting error `Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' ` – S M Apr 05 '16 at 07:20

3 Answers3

7

Change it to T obj = default(T);.

diiN__________
  • 7,393
  • 6
  • 42
  • 69
4

you have to write T obj = default(T); to assign the variable with a initial value

Byyo
  • 2,163
  • 4
  • 21
  • 35
0

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