43

I'm trying to use the Array.Contains () method in C#, and for some reason it's failing to compile, eve though I believe that I'm using C# 4.0, and C# should support this in 3.0 and later.

if (! args.Contains ("-m"))
    Console.WriteLine ("You must provide a message for this commit.");

And I get this error:

Main.cs(42,15): error CS1061: 'System.Array' does not contain a definition for 'Contains' and no extension method 'Contains' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

I am compiling from the command line, with no options: "csc Main.exe".

1
  • 11
    Read the error message. It is telling you what is wrong. You are missing either an assembly reference or a using directive. Commented Apr 30, 2011 at 0:41

6 Answers 6

82

You need to add using System.Linq; at the beginning of your program.

Sign up to request clarification or add additional context in comments.

Comments

13

Did you forget using System.Linq?

By the way, if you can't use LINQ there are many other options such as Array.Exists.

1 Comment

Or Array.Contains, which does the same thing as he wants. But he's obviously using C# 3.5 so no reason why he couldn't use Linq.
9

If you dont' want to use linq try

((IList<string>)args).Contains("-m")

Comments

5

The answers saying to include System.Linq are spot on, however there is one other cause of this problem. If the type of the argument for .Contains() does not match the type of the array, you will get this error.

public class Product
{
    public long ProductID {get;set;}
}

public IEnumerable<Product> GetProductsByID(int[] prodIDs)
{
    using (var context = new MyDatabaseContext())
    {
        return context.Products.Where(product => prodIDs.Contains(product.ProductID)); // ['System.Array' does not contain a definition for 'Contains'] error because product.ProductID is long and prodIDs is an array of ints.
    }
}

1 Comment

This was exactly the problem I had. I kept looking at that using statement looking for typos. Confusing!
3

I had the same issue and I had

using System.Linq

It was because I was trying to compare string to int, but somehow it was saying

'System.Array' does not contain a definition for 'Contains'

Comments

0

Make sure you are using correct version of CSC (csc /?) - you need 2010 version to compile for 4.0. You also may need to add additional libraries (/r option) for compile to succeed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.