Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Use of unassigned local variable" in a Generic Method

Tags:

c#

generics

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;
}
like image 900
Evan Larsen Avatar asked Feb 06 '11 00:02

Evan Larsen


1 Answers

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();
    }
}
like image 192
SLaks Avatar answered Dec 22 '22 21:12

SLaks