-2

I have two C# solutions in VS 2012.

The following explicit conversion works in both solutions:

Excel.Range rng = (Excel.Range)Date.DataRange.Cells[1];

The following implicit conversion works in one of the solution but generates an error in the other solution:

Excel.Range rng = Date.DataRange.Cells[1];

What might be the reason why the implicit conversion works in one of the projects but not the other?

EDIT: The error message that I get is 'object' does not contain a definition for 'Group' and no extension method 'Group' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    Have a look at the "Build" tab for the project properties, and see what the "Warning level" and "treat warnings as errors" options are set to. – rory.ap Jul 06 '15 at 16:38
  • 2
    Might help if we knew specifically what exception you are getting "generates an error" really doesn't give us much to go on. – Kevin Jul 06 '15 at 16:59
  • There are too many possible answers, given the vague question. Please provide additional details, including the _exact_ text of any warning or error messages you get from the compiler. – Peter Duniho Jul 06 '15 at 17:24
  • That error message is for trying to access a member that *you're not ever accessing in the code shown*, meaning that the error is due to a different code snippet. – Servy Jul 06 '15 at 17:29

1 Answers1

1

.NET 4 added dynamic and the ability to embed COM interop types into your assembly so the client doesn't need the very large PIAs installed or distributed.

These two features interact quite nicely, too, and I think this is where the difference is in your projects. If you enable 'Embed Interop Types' for an assembly, then the compiler will map the COM variant type to dynamic rather than object. This allows you to make use of the dynamic typing to implicitly cast return values as you are doing in your second example.

To enable 'Embed Interop Types', simply change the value to True in the Properties of the Microsoft.Office.Interop.Excel reference in the project in question.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • That is the solution. But I don't quite understand what true or false does and why setting it to true or false would be better. If you have a link at hand that talks about this in a way that a novice programmer might understand, please share a link. Anyway, thank you for clearing this up! – user1283776 Jul 06 '15 at 19:19
  • 1
    The answer to [this question](http://stackoverflow.com/questions/20514240/whats-the-difference-setting-embed-interop-types-true-and-false-in-visual-studi) has a bit more information. – Charles Mager Jul 07 '15 at 08:45