I am using the Visio API to loop through each Microsoft.Office.Interop.Visio.Master object in a Microsoft.Office.Interop.Document's Masters collection.
When I use var as follows, the compiler only recognizes master as type object and throws an error:
foreach (var master in doc.Masters)
Instead, I have to do this for it to work:
foreach (Visio.Master master in doc.Masters)
Why is this happening? Usually I have no problems using var in a foreach loop.
Edit: the error I get when I use the Open method on master is:
'object' does not contain a definition for 'Open' and no extension method 'Open' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
My guess is that doc.Masters is returning IEnumerable or IEnumerable<object> - i.e. it's weakly typed.
Basically there's an implicit cast in the second version - it's doing (assuming the non-generic form):
using (IEnumerator enumerator = doc.Masters.GetEnumerator())
{
while (enumerator.MoveNext())
{
Visio.Master master = (Visio.Master) enumerator.Current;
// Loop body
}
}
It only knows what type you're interested in because you've specified that as the type for the variable. (This is a bit like specifying the type of a range variable, which makes the compiler call Cast<T>() in the expansion of a LINQ query expression.)
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