C# / this. and List<T>
Posted
by
user3533030
on Stack Overflow
See other posts from Stack Overflow
or by user3533030
Published on 2014-06-02T15:23:08Z
Indexed on
2014/06/02
15:24 UTC
Read the original article
Hit count: 156
I am having trouble understanding how to initialize a List of objects and use it with methods inside of a class. I understand the mechanics of the List, but not how to initialize it inside a method and use it later.
For example, I want to have a class that creates the List when it is constructed. Then, I want to use a method of that class to add elements to the list. The elements in the list are objects defined by the SolidWorks API.
So, to construct the List, I used...
public class ExportPoints : Exporter
{
public List<SldWorks.SketchPoint> listOfSketchPoints;
public ExportPoints(SldWorks.SldWorks swApp, string nameSuffix) :
base(swApp, nameSuffix)
{
List<SldWorks.SketchPoint> listOfSketchPoints = new List<SldWorks.SketchPoint>();
}
public void createListOfFreePoints()
{
try
{
[imagine more code here]
this.listOfSketchPoints.Add(pointTest);
}
catch (Exception e)
{
Debug.Print(e.ToString());
return;
}
}
This fails during execution as if the listOfSketchPoints was never initialized as a List.
So, I tried a hack and this worked:
public ExportPoints(SldWorks.SldWorks swApp, string nameSuffix) :
base(swApp, nameSuffix)
{
List<SldWorks.SketchPoint> listOfSketchPoints = new List<SldWorks.SketchPoint>();
this.listOfSketchPoints = listOfSketchPoints;
}
This approach creates the behavior that I want. However, it seems that I lack some understanding as to why this is necessary.
- Shouldn't it be possible to "initialize" a List that is a property of your object with a constructor?
- Why would you need to create the list, then assign the pointer of that new List to your property?
© Stack Overflow or respective owner