Reputation: 113
How can Pass List to a constructor
I trying like this
private void button1_Click(object sender, EventArgs e)
{
step2 st2 = new step2(list);
}
But what to write in constructor definition
public step2()
{
InitializeComponent();
}
Any suggestion is welcome
Upvotes: 0
Views: 9057
Reputation: 11166
The answer may depend on what class step2 inherits from or how you use it. In other words - if your class step2 needs a default constructor you should not replace the constructor but add another one:
public step2()
{
InitializeComponent();
}
public step2(IList<String> stringList) : this()
{
// do something with stringList
}
Upvotes: 0
Reputation: 2140
public class A
{
List<string> listParam1 = new List<string>();
public A(List<string> ListParam)
{
listParam1 = ListParam;
}
}
This is how a parameterized constructor looks like.
And you can initialize it as following:
List<string> param = new List<string>();
param.Add("One");
param.Add("Two");
A obj = new A(param);
Let me know if this was helpful.
Upvotes: 0
Reputation: 7341
This should be your class constructor to accommodate List:
public step2(List<T> list)
{
InitializeComponent();
}
And you can call this class as follows:
List<string> myList = new List<string>(); // You can choose your own data type.
step2 obj = new step2(myList);
Upvotes: 0
Reputation: 229
You could even just do:
public step2(List<T> list){}
To use the function as a generic funciton for all List item :)
Upvotes: 0
Reputation: 20286
You need to pass to constructor either List or any class/interface that List inhereit from. For example IList will be good as well.
public step2(List<T> list){ }
public step2(IList<T> list){ }
T is a Type.
Upvotes: 0
Reputation: 3200
Basically:
public step2(List<Type> list) {
}
But good practice is to set IList
as an argument type.
public step2(IList<Type> list) {
}
You can read there about passing interfaces instead of object.
Upvotes: 0
Reputation: 14618
You need to provide a constructor for the step2
type that takes a List<T>
public step2()
{
InitializeComponent();
}
Should be:
public step2(List<T> list)
{
//Do something with list
InitializeComponent();
}
Constructors C# Programming guide should come in handy
Upvotes: 1
Reputation: 2013
It is that simple
public step2(List<string> list)
{
InitializeComponent();
}
I highly recommend to read a book about the basics of c#
Upvotes: 3
Reputation: 70718
You need to define a parameter in the constructor. For example.
public step2(List<Type> list)
{
}
Where Type
is your list type, i.e. List<string>
Upvotes: 5