So I am new to C# and done some researching on how to do this but I still don't get it.
I have 2 files, file foo
and file bar
. File foo
is my main file and I want to use a function from inside bar
inside foo
. The function's purpose is not important because I am just playing around for now. As of now it is an alternative method to print text into the console. I am getting this error message when I try to execute the command csc foo.cs
:
foo.cs(9,13): error CS0103: The name 'message' does not exist in the current context
foo.cs
using System;
namespace main
{
class program
{
static void Main(string[] args)
{
message.print("Hello World!"); //line 9
Console.ReadLine();
}
}
}
bar.cs
using System;
namespace main
{
public class message
{
public void print(string Message)
{
Console.WriteLine(Message);
}
}
}
any help would be much appreciated
ALSO: note that both files are in the same directory and both classes are in the same namespace.
Because screenshot was requested
CodePudding user response:
using System;
namespace main
{
class program
{
static void Main(string[] args)
{
message m=new message();
m.print("Hello World!"); //line 9
Console.ReadLine();
}
}
}
CodePudding user response:
You should create class instance, and then call the method of that variable.
Not that class names should start with capital first letter.
Try this:
using System;
public class Program
{
public static void Main()
{
Message msg = new Message();
msg.print("Hello World!"); //line 9
Console.ReadLine();
}
public class Message
{
public void print(string Message)
{
Console.WriteLine(Message);
}
}
}
Here is a working solution. snippet
CodePudding user response:
Alternatively to the other answers, print
could be static. Also note that the C# convention is that file, namespace, class and method names are in upper camel case, while parameters are in lower camel case. Another convention is to name the file the same as the class.
Program.cs
using System;
namespace Main
{
class Program
{
static void Main(string[] args)
{
Message.Print("Hello World!");
Console.ReadLine();
}
}
}
Message.cs
using System;
namespace Main
{
public class Message
{
public static void Print(string message)
{
Console.WriteLine(message);
}
}
}
Edit:
Earlier I wrote that Main
must be public, because .NET Fiddle required it. However, this is apparently not generally the case.
CodePudding user response:
OK. I found an answer. There were many problems but at the end I had to change up the command I was using.
At first I was using csc foo.cs
then I changed it to csc foo.cs bar.cs
As of yet I am unsure of exactly why but I will provide updates when I figure it out.
There is a documentation for options for the csc command.