'string []' does not contain a definition for 'Cast'

I get an error message:

'string []' does not contain a definition for "Cast" and does not use the extension method "Cast", which takes the first argument of the type "string []" (do you miss the using directive or assembly references?)

on the following code snippet:

return mNames.Cast().ToArray(); 

What do I need to use directive directive or assembly? How to find out such things?

I am a noob in C # and .NET, I just copy the code to complete the task, so don't get too much technical knowledge.

+7
source share
5 answers

(1) Make sure you are working with C # 3.0 +

(2) Make sure your code contains:

 using System.Linq; 

(3) .Cast is a general method, you need to specify a type parameter, for example:

 return mNames.Cast<AnotherType>().ToArray(); 
+18
source

This usually happens when you are missing using System.Linq; at the top of the file.

You will also need to use .NET 3.5 or more for it to work. System.Linq is located in the System.Core.dll assembly, which is included by default in projects using .NET 3.5 or higher.

EDIT

Upon closer inspection, this code will never work as it is written, because the Enumerable.Cast() method is general and requires that you pass in the type that you are executing: for example. mNames.Cast<object>().ToArray();

+5
source

Usually you call the Cast<T>() extension method with a type argument, for example mNames.Cast<SomeType>() .

Anyway, mNames already seems string[] , so what do you want to give it away? There is no need to abandon object , because object[] can be assigned from string[] .

+2
source

Even if you are not explicitly using "Cast", this compilation error will also appear if you use Linq expressions and forget "using System.Linq;"

+2
source

use primary.AddRange(secondary);

-one
source

All Articles