Reputation: 19742
I am developing a library that initializes plain-old data objects from data retrieved from SQL Server stored procedures. One of its methods is the following one:
public static T RetrieveCompound<T, U>(string cmdText, params Parameter[] parameters)
where T : Header<U>, new()
where U : class, new() {
Box<T> headerBox = new Box<T>();
List<U> details;
Execute(cmdText, parameters, new Action<Row>[] {
SetReferenceAction<T>(headerBox) +
delegate(Row row) { details = headerBox.Value.Details; },
delegate(Row row) { details.Add(row.ToObject<U>()); }
});
return headerBox.Value;
}
The third parameter of Execute
is an array of Action<Row>
s. Although no static analyzer can programmatically prove it, because of the way the Execute
method was programmed, no delegate can be run before the ones preceding it in the array. That means that the delegate
delegate(Row row) { details.Add(row.ToObject<U>()); } // use
must necessarily run after the delegate
delegate(Row row) { details = headerBox.Value.Details; } // initialize
And, thus, the variable details
will necessarily be initialized before it is used.
But C# still complains: "Use of unassigned variable 'details'."
Is there any way to make C# not complain about uninitialized variables that are actually not?
I am beginning to think C# is not for me.
Upvotes: 3
Views: 190
Reputation: 9966
Initialising it to a null value is one way of going about it:
List<U> details = null;
Then you can assign the correct data to it when you need to use it.
Upvotes: 3