Reputation: 61
I have a very simple question. This being said, I have tried to solve it by searching through stackexchange's previously answered questions but I came up short. This is because I want to know how to tell the program's entry point to access other classes.
I had previously written a simple finite state machine but the code got congested because I did not know how to break it up into classes. In my new program, I am trying to break it up so it can be better managed.
The entry point starts off by accessing the class I created, NewState()
. If you run the code, you will observe that despite it compiling correctly, the function inside NewState()
does not produce the Console.WriteLine
statement I wanted it to.
So, my question is this:
How do I make my code access the static void State()
method within the NewState
class and display the Console.WriteLine
statement?
Program class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Finite_State_Machine_3
{
class Program
{
static void Main(string[] args)
{
new NewState();
}
}
}
NewState class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Finite_State_Machine_3
{
class NewState
{
static void State()
{
Console.WriteLine("Hello world");
}
}
}
Upvotes: 0
Views: 97
Reputation: 4480
The method is static, so instead of creating an instance, make the State
method public and try this
static void Main(string[] args)
{
NewState.State();
}
But if you're going to be calling it like that, you'd probably be better off putting it in the same class.
class Program
{
static void Main(string[] args)
{
State();
}
static void State()
{
Console.WriteLine("Hello world");
}
}
If you do want it in a separate class and call it from an instance of that class, you need to make the State
method non-static (as well as public) and call it from the instance
class Program
{
static void Main(string[] args)
{
NewState MyVariable = new NewState();
MyVariable.State();
}
}
class NewState
{
public void State()
{
Console.WriteLine("Hello world");
}
}
Upvotes: 3
Reputation: 77637
You need to make the method public static
or internal static
, then just call it by invoking NewState.State()
Upvotes: 0
Reputation: 36319
If it's static, then you'll call it from the class not from the instance.
So,
NewState.State()
That said, if I remember my design patterns right you actually want to be passing instances around, not using static methods.
Upvotes: 0