Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I am getting the error:

'string[]' does not contain a definition for 'Cast' and no extension method 'Cast' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)

on the following piece of code:

return mNames.Cast().ToArray();

What using directive or assembly reference do I need? How do I find out such things?

I'm a noob at C# and .NET, I'm just copying code to get a job done, so don't get too technical with me.

like image 247
Graham Avatar asked Jun 27 '12 08:06

Graham


2 Answers

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

(2) Make sure your code contains:

using System.Linq;

(3) .Cast is a generic method, you need to specify the type parameter, like this:

return mNames.Cast<AnotherType>().ToArray();
like image 131
Cheng Chen Avatar answered Sep 18 '22 17:09

Cheng Chen


That usually happens when you're missing using System.Linq; at the top of your file.

You'll also need to be using .NET 3.5 or greater for it to work. System.Linq is in the assembly System.Core.dll, which is included by default in projects that use .NET 3.5 or higher.

EDIT

On closer inspection, that code will never work as written, because the Enumerable.Cast() method is generic, and requires you to pass in the type that you are casting to: e.g. mNames.Cast<object>().ToArray();

like image 23
Bennor McCarthy Avatar answered Sep 18 '22 17:09

Bennor McCarthy