newbie question: multiple methods in console app

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

I'm making the move from vb to C# and am writing some sample code in a
console app. I wanted to write a number of methods each with a different
example test code. the from the main function I wanted to call one of these
test methods. Are additional methods or funtions allowed in a console app?
I'm having trouble referencesing a function from the main function. Can
someone please advise what I should do?

Thanks.

Here's my sample code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test();
//compile error on test().
//Err: The name 'Test' does not exist in the current context
}

public void Test()
{
Console.WriteLine("its working now");
}
}
}
 
moondaddy,

Yes, you can create other methods. You have to declare them as static,
since your Main method is static. The reason you don't notice this in VB is
because in vb, your methods were in a module file, which automatically makes
the methods, fields, and properties declared in there static.

Hope this helps.
 
Yes you can: just mark Test() as "static"

i.e.

public static void Test() {
Console.WriteLine("its working now");
}

"static" means that this function doesn't require an instance of the class
(Program in this case); Main() is always a static method, so it must either
call static methods, else create an instance of something an then call
methods on that instance. I've gone down the first route.

Marc
 
Thanks this helps!

--
(e-mail address removed)
Nicholas Paldino said:
moondaddy,

Yes, you can create other methods. You have to declare them as static,
since your Main method is static. The reason you don't notice this in VB
is because in vb, your methods were in a module file, which automatically
makes the methods, fields, and properties declared in there static.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

moondaddy said:
I'm making the move from vb to C# and am writing some sample code in a
console app. I wanted to write a number of methods each with a different
example test code. the from the main function I wanted to call one of
these test methods. Are additional methods or funtions allowed in a
console app? I'm having trouble referencesing a function from the main
function. Can someone please advise what I should do?

Thanks.

Here's my sample code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test();
//compile error on test().
//Err: The name 'Test' does not exist in the current context
}

public void Test()
{
Console.WriteLine("its working now");
}
}
}
 
Back
Top