Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Fri May 20, 2016 4:16 am

I've been using var a lot in my recent C# coding.

Why doesn't the following work:

foreach (var section in templateDoc.Sections)

Specifying Section does
foreach (Section section in templateDoc.Sections)

and so does casting.
foreach (var section in templateDoc.Sections.Cast<Section>())

I've never had to cast anything before, and I haven't had any trouble with var. Why is using var an issue?

carl_heller
 
Posts: 5
Joined: Thu May 19, 2016 7:14 pm

Fri May 20, 2016 7:04 am

Hi,

Thanks for your posting.
Is your issue that the line foreach (var section in templateDoc.Sections) has error on your side? Could you please give us further detail? But I just tested the way and it can work. Becasue any object can use var, so if you want to use property and method of certain object, it must first be into its type.

Best Regards,
Amy
E-iceblue support team
User avatar

amy.zhao
 
Posts: 2766
Joined: Wed Jun 27, 2012 8:50 am

Wed May 25, 2016 2:57 pm

If I use
Code: Select all
             foreach (var section in templateDoc.Sections)
                {
                    foreach (var table in section.Tables)

I get a compile error in Visual Studio stating that 'object' does not contain a definition for Tables.

I need to use a Cast for it to work:

Code: Select all
            foreach (var section in templateDoc.Sections.Cast<Section>())
                {
                    foreach (var table in section.Tables.Cast<Table>())

I have checked and I am using version 5.7, downloaded from NuGet.

carl_heller
 
Posts: 5
Joined: Thu May 19, 2016 7:14 pm

Thu May 26, 2016 1:52 am

Hi,

Thanks for your further posting.
As I mentioned early that it must first be into its type when using property and method of certain object. So it should be
foreach (Section section in templateDoc.Sections), and then section.Tables will work.

Best Regards,
Amy
E-iceblue support team
User avatar

amy.zhao
 
Posts: 2766
Joined: Wed Jun 27, 2012 8:50 am

Return to Spire.Doc