In Create()
you are creating a class but, as you say, not able to us it outside of the class. The first thing you need to do is to change it to return the object:
public SomeType Create()
{
//code that creates the object here.
//Lets say it gets put into a variable called ret
return ret;
}
public void Use()
{
SomeType st = Create();
//use st here.
}
Alternatively, instead of the method that uses the object calling Create
, the method that creates the object could pass it as a parameter to Use(SomeType st)
.
To do this with multiple objects, then we need to return not a SomeType, but an object that contains those multiple SomeType objects. Sometimes we need certain properties and methods about that entire collection (e.g. the count, the ability to move back and forward through the collection and so on). In this case we would return an array, a List<SomeType>
, a HashSet<SomeType>
or perhaps something like Dictionary<string, SomeType>
as appropriate.
If we don't need such operations on the collection as a whole then it is simpler and more efficient to return an IEnumerable<SomeType>
which is an object that allows one to work through a sequence of such objects but not much else. C# has a syntax precisely for doing this. Say we're going to return 10 such objects:
public IEnumerable<SomeType> Create()
{
for(int i = 0; i != 10; ++i)
{
//code that creates the object here.
//Lets say it gets put into a variable called ret
yield return ret;
}
}
public void Use()
{
foreach(SomeType st in Create())
{
//use st here.
}
}
The yield
keyword nicely hides a lot of complexity about IEnumerable<SomeType>
and lets you just write the code that passes out each new object (that complexity is still there in the produced code, but not your problem to worry about).