Lists as Parameters?

So, working through my project I stumbled upon a number of answers here that suggested that when possible I should use Lists instead of ArrayLists to hold data, so I went through and converted the various sections of code to support a List.

Then I got stuck. :frowning:

Iā€™m pretty new to C#, Unity and scripting in general, so pardon Newbie mistakes!

public string ListContents<inputType> (List<inputType> iList)
{
	string invList = null;
	if(iList != null){
		foreach (string item in iList) {
			invList = string.Concat (invList, " ", item);
		}
		if(invList != null){
			invList=invList.Trim();
		}
	}
	return invList;
}

Code is intended to to take in an Item Inventory from my Player Manager script as a param, generate a concat string of the content and chuck it back out as the return for the GUI function calling it later on.

GUI.Label (new Rect (10, 50, 250, 100), ListContents (PlayerManager.ItemInventory));

Problem is with the functionā€™s first line, I get various errors based on the variation I try with no real understanding of which I should be working with and why theyā€™re throwing errors.

I started with:

public string ListContents (List iList)

Error CS0246: The type or namespace name `Listā€™ could not be found. Are you missing a using directive or an assembly reference?

Which gave me the reminder to add ā€œusing System.Collections.Generic;ā€ to the top of my code, but still it persisted. I found some answers leading down the ā€œGenericā€ route:

public string ListContents<string> (List<string> iList)

Error CS0081: Type parameter declaration must be an identifier not a type

public string ListContents<inputType> (List<inputType> iList)

Error CS0030: Cannot convert type inputType' to stringā€™

But ultimately I donā€™t really want a generic, I chose Lists to be strongly typed, so why circumvent that?

Generic lists are still strongly typed- the reason you are getting all these errors is because you are treating them like they arenā€™t!

The main problem here, is that you are using a generic method, and then assuming that the list will always be a list of strings. It doesnā€™t like that, because it needs to remain as general as it can possibly be. In your case, you should just specify the desired type and be done with it.

public string ListContents (List<string> iList)

Of course, since every type must have a ā€˜ToStringā€™ method, you could still do it like this-

public string ListContents<inputType> (List<inputType> iList)
{
    string invList = null;
    if(iList != null){
       foreach (inputType item in iList) {
         invList = string.Concat (invList, " ", item.ToString());
       }
       if(invList != null){
         invList=invList.Trim();
       }
    }
    return invList;
}