Use of Unassigned local variable 'model'. Is what error message I'm getting. Its right where I say if (model == null). I'm not sure why its giving me a compile time error there.. someone please help.
public static T TryGet<T>(string fileName) where T : new()
{
T model;
using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storageFile))
{
if (stream.Length > 0)
{
var serializer = new DataContractSerializer(typeof(T));
model = (T)serializer.ReadObject(stream);
}
}
}
if (model == null)
{
model = new T();
}
return model;
}
As the error states, you cannot use a local variable until the compiler can prove that it has been assigned a value.
In your case, if your if
condition is false, the model
variable is never assigned.
You can solve the problem by assigning it an initial valued first:
T model = default(T);
Note that if T
is a struct type, model == null
can never be true.
You should change your code to
using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storageFile))
{
if (stream.Length > 0)
{
var serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(stream);
}
else
{
return new T();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With