Trick when using Array.Contains() C# 2.0

AID: 7412
  • Status: Published

1370 points

  • Bysonawanekiran
  • TypeTips/Tricks
  • Posted on2011-09-08 at 04:39:34
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this?
string[] stuff = ....;
if (stuff.Contains(“item”))
{
    ...
}
                                    
1:
2:
3:
4:
5:

Select allOpen in new window



In .NET 3.5, this is possible out of the box (make sure you reference System.Core and include the System.Linq namespace) but if you try to run this code in .NET 2.0 or .NET 3.0, you will get errors. Nevertheless the .NET Framework 2.0 does provide a Contains() method on any Array object.

In the .NET Framework 2.0, System.Array implements the System.Collections.Generic.IList<T> interface. Unfortunately the implementation of the IList interface is provided at runtime, so we do not see the methods in Visual Studio and we cannot write array.Contains().

Instead, we have to cast the array to the appropriate IList interface:

string[] arr = new string[] { “RR US”, “RR India”, “RR UK” };
if (!((IList<string>)arr).Contains(“India”))
{
     System.Console.WriteLine ("Correct! We are working with RR India");
}
                                    
1:
2:
3:
4:
5:

Select allOpen in new window



The documentation explains it as follows:

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.


So next time, you can save yourself from writing (unnecessary) code like this:

bool found =false;
    foreach (string s in array)
    {
        if (s.Equals(“item”))
        {
            found =true;
            break;
        }
    }
    if (found)
    {
       ........
    }
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window



Some of you guys might have an alternate solution for this.
For example

bool exists = Array.IndexOf(arr, "RR India") >= 0
                                    
1:

Select allOpen in new window


No doubt this is an alternative solution solutions. This may differ in terms of performance. But, this is for c# 2.0 and as explained above .NET Framework 2.0 does provide a Contains() method on any Array object. So this may helpful for framework wise comparison.

Happy Programming!!!
Asked On
2011-09-08 at 04:39:34ID7412
Tags

C# .net

Topic

.NET

Views
590

Comments

Expert Comment

by: RETAILREALM on 2011-09-25 at 22:30:18ID: 31820

This is good stuff. Great work!!!

Expert Comment

by: meeran03 on 2011-11-20 at 01:59:58ID: 33252

always good to have plan b for any solution .
i will definitely use this in future ...
thanks..

Expert Comment

by: apuma on 2012-02-08 at 14:49:45ID: 42334

I have found that in some cases using a dictionary object is useful, (as of 3.5?) you can call contains , or countainsKey to check either objects or keys. and since it is a based on a hashmap, the containskey is extremely fast in large lists [compared to standard arrays, lists].  since the dictionary constructor specifies the object type for the list you also maintain all the intelisense for the objects, as apposed to a standard hashmap (or is it hashtable?) which only returns Object class Objects

Expert Comment

by: nepaluz on 2012-02-15 at 10:18:21ID: 43037

The problem you describe is NOT limited to .NET 2.0, infact, the same happens with .NET 4.5 on arrays and arraylists. Lists dynamically typecast values inside them in LINQ whereas this is not the case with arrays. The cure you prescribe, though, is correct.

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top .NET Programming Experts

  1. CodeCruiser

    588,856

    Sage

    6,000 points yesterday

    Profile
    Rank: Genius
  2. kaufmed

    377,702

    Wizard

    10 points yesterday

    Profile
    Rank: Genius
  3. BuggyCoder

    268,007

    Guru

    1,600 points yesterday

    Profile
    Rank: Sage
  4. TheLearnedOne

    232,552

    Guru

    4,900 points yesterday

    Profile
    Rank: Savant
  5. Idle_Mind

    193,005

    Guru

    0 points yesterday

    Profile
    Rank: Savant
  6. JamesBurger

    156,812

    Guru

    2,000 points yesterday

    Profile
    Rank: Sage
  7. wdosanjos

    124,308

    Master

    2,000 points yesterday

    Profile
    Rank: Genius
  8. Dhaest

    115,720

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. sedgwick

    112,918

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  10. nepaluz

    101,325

    Master

    0 points yesterday

    Profile
    Rank: Sage
  11. MlandaT

    95,921

    Master

    2,100 points yesterday

    Profile
    Rank: Genius
  12. navneethegde

    74,442

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  13. Masteraco

    70,367

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  14. binaryevo

    70,365

    Master

    0 points yesterday

    Profile
    Rank: Guru
  15. ambience

    69,104

    Master

    0 points yesterday

    Profile
    Rank: Sage
  16. emoreau

    68,230

    Master

    0 points yesterday

    Profile
    Rank: Genius
  17. PaulHews

    49,486

    0 points yesterday

    Profile
    Rank: Genius
  18. AndyAinscow

    45,290

    0 points yesterday

    Profile
    Rank: Genius
  19. Chinmay_Patel

    43,411

    0 points yesterday

    Profile
    Rank: Genius
  20. ged325

    41,700

    2,600 points yesterday

    Profile
    Rank: Genius
  21. RolandDeschain

    41,317

    0 points yesterday

    Profile
    Rank: Sage
  22. nishantcomp2512

    39,486

    0 points yesterday

    Profile
    Rank: Wizard
  23. tommyBoy

    36,550

    0 points yesterday

    Profile
    Rank: Genius
  24. mroonal

    35,000

    0 points yesterday

    Profile
    Rank: Sage
  25. santhimurthyd

    34,650

    0 points yesterday

    Profile
    Rank: Wizard

Hall Of Fame