Reputation: 49
My idea here is to create a text based adventure game.
I'm trying to use a class in my main class. While I'm trying to, it gives me the error:
'MyAdventure.Window' is a 'type' but is used like a 'variable'
I'm not sure on how to solve this. I tried creating a new instance of the class but it didn't seem to work. I am fairly new to this, but could anyone please help?
Thanks in advance.
Here's the code for my main class (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyAdventure
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("You cannot feel your body. You don't know where you are.\nThe room you're in is dark. You cannot see much.");
Console.WriteLine("You decide to stand up, and take a look around. You see a door and a window.\nWhich do you check out first?");
Console.WriteLine("A. Window\nB. Door");
string userInput = Console.ReadLine();
//Window theWindow = new Window();
if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
{
Window();
}
else if (userInput.StartsWith("B", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("You chose the door.");
}
Console.ReadKey();
}
}
}
And this is the code (so far) for the other class Window.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyAdventure
{
public class Window
{
static void theWindow()
{
Console.WriteLine("You approach the window.");
Console.ReadKey();
}
}
}
Upvotes: 0
Views: 16912
Reputation: 216273
The correct syntax to call a static method of a class is the following
if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
{
Window.theWindow();
}
You can't use simply the name of the class, but you should specify the static method to call (one from potentially many methods)
Also the method 'theWindow' should be made public otherwise is private by default inside a class
access level for class members and struct members, including nested classes and structs, is private by default
public static void theWindow()
{
Console.WriteLine("You approach the window.");
Console.ReadKey();
}
Upvotes: 3
Reputation: 26386
theWindow()
is a static method. Static members are called like ClassName.MethodName()
, in your case Window.theWindow()
When you did Window theWindow = new Window();
, you were creating an instance of the Window
class. Static members cannot be access from instance of a class.
To call that method from an instance, you need to remove the static
modifier
public class Window
{
public void theWindow()
{
Console.WriteLine("You approach the window.");
Console.ReadKey();
}
}
Usage
Window w = new Window(); //creating an instance of Window
w.theWindow();
Upvotes: 1
Reputation: 62248
You may need to call
....
...
if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
{
Window.theWindow();
}
...
...
Upvotes: 0