473,626 Members | 3,933 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

generic method that tests if array contains a value

Is it possible to write a generic method which returns true or false,
depending on if the array contains a value?

Is there already a framework method that provides this functionality?

the following code does not compile. Error is: Operator == cannot be
applied to operands of type T and T.

public static bool Contains<T>(T[] InValues, T InPattern)
{
bool doesContain = false;
foreach (T vlu in InValues)
{
if (vlu == InPattern)
{
doesContain = true;
break;
}
}
return doesContain;
}

May 10 '07 #1
2 5052
"Steve Richter" <St************ @gmail.comwrote in message
news:11******** **************@ p77g2000hsh.goo glegroups.com.. .
the following code does not compile. Error is: Operator == cannot be
applied to operands of type T and T.
You can get it to compile if you use Equals instead of == :

if (vlu.Equals(InP attern))
{
doesContain = true;
break;
}

If the class <Tdoes an adequate override of Object.Equals, then you
will get a meaningful behaviour. Otherwise, Equals defaults to calling
ReferenceEquals , which will consider the two elements you are comparing to
be equal if they contain the same reference, and will consider that they are
different if the reference is different, regardless of wether the contents
are equal or not. This may or may not be adequate for your needs, depending
on what <Tis and what you want to do with it.
May 10 '07 #2
Well, you could use Array.IndexOf<T >(array, instance) >= 0...

However, ICollection<Tha s a Contains(T) method, and T[] :
ICollection<T>, hence (and more re-usable, if trivial):

static void Main() {
int[] values = { 1, 2, 3, 4, 5 };
Console.WriteLi ne(Contains(val ues, 3));
Console.WriteLi ne(Contains(val ues, 6));
}
static bool Contains<T>(ICo llection<Tdata, T value) {
if (data == null) throw new ArgumentNullExc eption("data");
return data.Contains(v alue);
}

Marc
May 10 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3077
by: cody | last post by:
I know I can use ArrayList.ReadOnly() to create a readonly version of it, but how can I achive a similar thing with a generic collection of .NET 2.0?
8
1825
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
11
14504
by: ZenRhapsody | last post by:
Has anyone done any performance testing between new generic Lists and single dimensional arrays? I really like the code flexibility the List provides since I don't know how many items I will have in the list. With my array approach, I have to manage re-sizing the array myself. So, is using List<myClass> x as fast as MyClass x ?
4
2216
by: Adam Clauss | last post by:
I ran into a problem a while back when attempting to convert existing .NET 1.1 based code to .NET 2.0 using Generic collections rather than Hashtable, ArrayList, etc. I ran into an issue because the old code allowed me to do what basically was the following assignment: class SomeClass { private Queue q; SomeClass(Queue q)
0
5924
by: crazyone | last post by:
I've got a gaming framework i'm building and i want to save myself the trouble of reading and writting the complete game data to a custom file and load/save it to an XML file but i'm getting problem serializing my stuff to XML when it comes to collections. I'm currently using .net2 with generic lists to prevent users putting all sorts of stuff in the arrays (Although im sure i'll be the only user of the classes but not the game, anyway)....
2
10698
by: Stephen Costanzo | last post by:
I have: Public Class test Private displayValue As String Private dbType As Integer Property Display() As String Get Return displayValue End Get
0
13294
by: JosAH | last post by:
Greetings, I was asked to write a Tip Of the Week; so here goes: a lot of topics are started here in this forum (and a lot of other forums too) mentioning a problem about sorting data. Examples of two main problem scenarios are like this: 1) an array containing a first name and another array containing a last name and possibly a third array containing the age of a person; how to sort the
11
1888
by: Bob Altman | last post by:
Hi all, I want to write a generic class that does this: Public Class X (Of T) Public Sub Method(param As T) dim x as T = param >3 End Sub End Class
26
3607
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic delegate type expression in just the right place and a well-named method means we can almost read the code out loud and understand it without even thinking. Note that since 'boxing' and 'unboxing' is involved (I think), you don't get what you...
0
8199
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8365
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8505
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7196
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5574
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2626
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.