Which is less than ideal, because you have to remember to do it in the form's constructor for every project which references the class library.Cags said:Unless I'm mistaken, you can't initialise a class library because it isn't an object. The simplest way to initialise objects within a class library is to have a static (shared) method called Initialise, which you would call at some point before you would require the objects, in your forms contructor for example.
public static class MyClass
{
static List<int> _list = null;
public int[] MyArray
{
get
{
if (_list == null)
{
// _list has not been initialized yet...
_list = new List<int>();
_list.Add(100);
_list.Add(200);
_list.Add(300);
}
return _list.ToArray();
}
}
}
Gill Bates said:Just do something like this:C#:public static class MyClass { static List<int> _list = null; public int[] MyArray { get { if (_list == null) { // _list has not been initialized yet... _list = new List<int>(); _list.Add(100); _list.Add(200); _list.Add(300); } return _list.ToArray(); } } }
Well, that's exactly what you want to do isn't it?You can only use it for variables within a procedure that you want to have retain their value across calls to that procedure.
Public Class TestClass
Private Shared _list As System.Collections.Generic.List(Of Integer) = Nothing
Public Shared ReadOnly Property MyArray() As Integer()
Get
If _list Is Nothing Then
Console.WriteLine("List created...")
_list = New System.Collections.Generic.List(Of Integer)
_list.Add(100)
_list.Add(200)
_list.Add(300)
End If
Return _list.ToArray()
End Get
End Property
End Class
Console.WriteLine(TestClass.MyArray.Length)
Console.WriteLine(TestClass.MyArray.Length)
You would declare a Shared Sub New in the class that contains the list and initialize the list from that sub.rbulph said:Where can you put initializations code for a class library? I've got a List of objects which I use in the class library and I want to initialize it with data. Where would I call this from?