List.Contains Method wont work.

I have a list called selMods. It’s a list of type Option which is a class I made that just contains some information. Here is the class in it’s entirety.

public class Option {
	
	public string Name;
	public bool IsActive = true;
	public int ID;

	private Option(){}

	public Option(string name){
		Name = name;
	}

	public Option(string name, int id){
		Name = name;
		ID = id;
	}
}

The selMods list is filled with Options that only have a string name specified. The ID for these options is always null. (There are other options that do require an ID.)

The list is populated depending on what the user selected. In some cases I need to know if a certain option was selected.
For example an option with the string name “Disable Research”. Now I know for a fact that selMods contains an Option with the name “Disable Research”, I selected that option myself.
But when I want to check it in the code I can’t manage to get it work.

I tried 2 things, based on the documentation for List.Contains List.Contains .

	if(selMods.Contains(new Option { Name = "Disable Research"})){
		Debug.Log("Found Disable Research");
	}

If I try it this way, I simply get the following error: Assets/Scripts/Generator.cs(285,77): error CS1729: The type Option' does not contain a constructor that takes 0’ arguments

It has a private constructor that takes 0 arguments, which is purely for XMLSerialization stuff, but I don’t understand why it gives me this error. I’m not looking for an Option with 0 arguments, I’m looking for an Option with 1 argument, right?

The second thing I tried is:

if(selMods.Contains(new Option ("Disable Research"))){
	Debug.Log("Found Disable Research");
}

This doesn’t give me any errors but the debug.log is never run, even though I know for a fact that the option is inside selMods.

Could somebody be so kind to tell me what I did wrong? I just need to check if the list contains an option with the string name “Disable Research”.

So if you look at the documentation from MSDN, you will notice that they Implemented IEquatable on the Part class. This is VERY VERY important as they override the general ability of List.Contains method that would compare references(if of reference type) and had it compare PartId’s to check to see if the list contains a Part object with that part type. Again without a comparer implemented it will compare the internal references(does it point to the same object).

Now you could use LINQ to get the job done.

using System.Linq; // <-- you need that name space

...

if (selMods.Any(opt => opt.Name.Equals("Disable Research", StringComparison.InvariantCultureIgnoreCase))) {
  Debug.Log("Found Disabled Research");
}

...

In the case above, we iterated over the collection(read List) and checked each item for an Option object with a name of “Disable Research”, case-insensitive.

List.Contains is not the same as a string.Contains.