Paul Michaels
Paul Michaels

Reputation: 16695

Store list of forms in an array

I have a program that needs to navigate through a series of screens in a given order. What I’d like to do is to manage this centrally, using something analogous to a class factory, where I send a request for the next form, and it instantiates and returns the next form. I have the following, however, this will instantiate all the forms immediately:

private List<Form> screens = new List<Form>() { new Form1(), new Form2(), … };
private Form currentForm;
private int currentPos;

public Form Next()
{            
    currentForm = screens[++currentPos];
    return currentForm;
}

Is there a way to defer instantiation until the actual request is made? For example:

private List<Form> screens = new List<Form>() { Form1,Form2, …};
private Form currentFrm;
private int currentPos;

public Form Next()
{            
    currentForm = new screens[++currentPos];
    return currentFrm;
}

(this won't compile)

Upvotes: 2

Views: 2578

Answers (4)

James Gaunt
James Gaunt

Reputation: 14783

Another option...

public IEnumerable<Form> Forms
{
    yield return new Form1();
    yield return new Form2();
    yield return new Form3();
    ...    
}

Upvotes: 0

abatishchev
abatishchev

Reputation: 100278

private List<Type> screens = new List<Type>() { typeof(Form1), typeof(Form2), … };

Type t = screens[++currentPos];
return (Form)Activator.CreateInstance(t);

Upvotes: 0

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262949

One way to do that is to store types in your list and use Activator.CreateInstance() to dynamically create the form instances:

private Type[] screenTypes = new Type[] {
    typeof(Form1),
    typeof(Form2),
    ...
};

private Form currentForm;
private int currentPos;

public Form Next()
{            
    currentForm = (Form) Activator.CreateInstance(screenTypes[++currentPos]);
    return currentForm;
}

Upvotes: 2

leppie
leppie

Reputation: 117250

You could use a list of delegates, eg:

List<Func<Form>> screens = new List<Func<Form>>
{
  () => new Form1(),
  () => new Form2(),
  ...
};

Upvotes: 0

Related Questions