Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble adding custom class to list (C#)

Tags:

c#

list

class

I hope my terminology is correct here, still learning all the right lingo.

I've created a custom class using the following code:

    public class inputData
{
    public string type;
    public int time;
    public int score;
    public int height;
}

And I'd like to create a list that contains that class, as I've done here:

List<inputData> inputList = new List<inputData>();

I'm now trying to Add to that list and I'm having trouble. I've tried both of the following and still no luck. Can someone point me in the right direction here?

inputList.Add(new inputData("1", 2, 3, 4));

inputList.type.Add("1"); 
like image 232
areeved Avatar asked Nov 12 '12 06:11

areeved


2 Answers

You need object initializer

Change

inputList.Add(new inputData("1", 2, 3, 4));

To

inputList.Add(new inputData{type="1", time=2, score=3, height=4});
like image 144
Adil Avatar answered Oct 04 '22 00:10

Adil


Problem isn't with the list, but with the inputData class - you're trying to use undefined contructor. Add the contructor into the inputData class:

public inputData(string type, int time, int score, int height)
{
  this.type=type; this.time=time, this.score=score, this.height=height
}

Second, follow C# conventions - name of class should start with uppercase, public field replace with C# properties. But it's not the problem your code doesn't work.

like image 43
Perun_x Avatar answered Oct 04 '22 00:10

Perun_x