I’m relatively inexperienced with C# in Visual Studio. I have created a class called Visitor and I want to track be able to access these visitors in different Forms. What would be the best way of doing this. I thought of having a Visitors class which was a list that could be accessed. However, I can’t seem to find a way of doing this. I get the following error
Error CS1955 Non-invocable member 'Visitors' cannot be used like a method.
He is the code for my Visitors Class…
namespace VisitorSignInSystem
{
public class Visitors
{
List<Visitor> current { get; set; }
public Visitors()
{
current = new List<Visitor>();
}
public Visitors(Visitor v) {
current.Add(v);
}
}
}
I initialise the list on the first form….
public Form1()
{
InitializeComponent();
Visitors();
}
And try and ass something to the list in a different form…
public VisitorSignInWelcome(Visitor v)
{
InitializeComponent();
Visitors(v);
}
Any help greatly appreciated or a signpost to the correct way of doing this please.
2
Answers
First of all, lets clean up your class a littlebit:
This ensures that the current list is always created. Note that there is not much point to such a class without additional methods or properties, I assume these have been omitted for brewity. Also consider removing the
Visitors
class completely, and just use aList<Visitor>
to represent multiple visitors.Next, lets actually create an object from our class and assign it to a field:
for the last part, lets share the same object between another form:
Note that this is just a very simple example of the basics. As soon as you start actually making the UI more advanced the complexity greatly increases. As an example, if Form2 makes changes to your visitors, it may need to inform Form1 so it can update itself so the changes are visible to the user.
You may also consider if there is some better term than "Visitor", since it may be conflated with the visitor-pattern, at least that is what I think of when I see a class named "Visitor".
It sounds like you want to create a Singleton VisitorsService that provides CRUD-like functionality for a list of visitors.
Put this service into your DI Container:
you can then inject IVisitorsService into a controller, class, etc., or can pull the singleton instance from the IServiceProvider that you inject.