How to initiate a public method in Main? - c#

Started learning C# today, but can't get my head around how to call functions/methods in Main.
If I were to have a few methods like the one i have created, and have them all in this file for the benefit of just having to write in one file, I would very much like to call them one by one, just to try them out.
So if I were to call, or initiate this DisplayMessage() within Main, how could I do that?
Since I am as green as it gets, I am also wondering if this would be considered bad practice? Do you always want to have your different classes, and/or functions in seperate files?
Here is what I have managed to produce/learn so far today:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
//Call DisplayMessage() here?
}
public void DisplayMessage()
{
string str1;
Console.WriteLine("Please enter your first name:");
str1 = Console.ReadLine();
Console.WriteLine("Hello {0}", str1);
Console.ReadLine();
}
}
}
Would be thankful if someone would help me (and hopefully others, with somewhat poor programming backround, like my self) out.

You can't call a non-static method from a static method. You need to either make the method static, or create an instance.
To make it static, use:
static void Main(string[] args)
{
DisplayMessage();
}
public static void DisplayMessage()
{
string str1;
// ...
Otherwise, you can create an instance, and call the method on the instance:
static void Main(string[] args)
{
var program = new Program();
program.DisplayMessage();
}

For simplicity, you can keep DisplayMessage() in there for testing it out.
Main is a static method, so you have to call other static methods (make DisplayMessage static), or you can instantiate the class that the non-static method is in:
static void Main(string[] args)
{
Program p = new Program();
p.DisplayMessage();
}
In the future, it'll make things simpler (and easier to test) if you keep them in different appropriately-named classes.

You need to mark the method static.
Since Main is static, you can only access other static members/methods from it.
So changing your function signature to this:
public static void DisplayMessage()
Will work.

The simple fix would be to make DisplayMessage() static:
public static void DisplayMessage()
....
static means that you don't have to create an instance of Program to use it, and your Main method is static, so you don't have an instance of Program.
The other way would be to create an instance of Program:
Program program = new Program();
program.DisplayMessage();

Related

Accessing Methods Within a Class (C#)

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");
}
}
}
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");
}
}
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.
You need to make the method public static or internal static, then just call it by invoking NewState.State()

Executing code before .NET's Main() method

Is it possible to execute any user-provided code before the .NET Main method?
It would be acceptable if the code had to be unmanaged.
The reason for asking is that this might be a way to solve the problem of calling SetCurrentProcessExplicitAppUserModelID before any UI elements are displayed (as mentioned in Grouping separate processes in the Windows Taskbar)
In C# you can add a static constructor to the class which contains the main method. The code in the static constructor will be executed before main.
A static constructor will execute before Main, but only if the class is actually being referenced by something. Eg:
class ClassWStaticCon
{
static ClassWStaticCon()
{
Console.WriteLine("Hello world!");
}
}
...
static void Main(string[] args)
{
Console.WriteLine("Hello main.");
}
Will print:
Hello main.
class ClassWStaticCon
{
public static int SomeField;
static ClassWStaticCon()
{
Console.WriteLine("Hello world!");
}
}
...
static void Main(string[] args)
{
ClassWStaticCon.SomeField = 0;
Console.WriteLine("Hello main.");
}
Will print:
Hello world! Hello main.
If you want to control the order of execution then use a Queue of Action delegates http://msdn.microsoft.com/en-us/library/018hxwa8.aspx in a single static 'initialize all pre main stuff' class.

Cannot call a function from a static method

Ok, this may sound like a very novice question.. i'm actually surprised i'm asking it. I can't seem to remember how to call a function from inside static void Main()
namespace myNameSpace
{
class Program
{
static void Main()
{
Run(); // I receive an error here.
Console.ReadLine();
}
void Run()
{
Console.WriteLine("Hello World!");
}
}
}
error:
An object reference is required for the non-static field, method, or property 'myNameSpace.Program.Run()'
You need to either make Run a static method or you need an object instance to call Run() of. So your alternatives are:
1.) Use an instance:
new Program().Run();
2.) Make Run() static:
static void Run()
{
/..
}
Declare your Run() method as static too:
static void Run()
{
Console.WriteLine("Hello World!");
}
Make method static: static void Run()
Run() must also be static or you need to create a new instance of the object like new Program().Run();
cause static function is not associate with an instance. while the none static function must have an instance.
So you have to create a new instance (each way you want) and then call the function.
The other way is to encapsulate your Run() method inside a nested class and invoke it.
static void Main(string[] args)
{
new NestedClass().Run();
}
class NestedClass
{
public void Run()
{
}
}

Can there be stand alone functions in C# without a Class?

In C/C++, I have a bunch of functions that I call from main(), and I want to rewrite this in C#. Can I have stand alone functions(methods) or do I have to put them in another class? I know I can have methods within the same class, but I want to have a file for each function/method.
Like this works:
using System.IO;
using System;
class Program
{
static void Main()
{
House balls = new House();
balls.said();
}
}
public class House
{
public void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
But then I have to create an instance of House and call said(), when in C I can just call said().
For reference, I want to add the using static addition of C# 6 here.
You can now use methods of a static class without having to type the name of that class over-and-over again. An example matching the question would be:
House.cs
public static class House
{
public static void Said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
Program.cs
using static House;
class Program
{
static void Main()
{
Said();
}
}
No. Make them static and put them in a static utility class if they indeed don't fit within any of your existing classes.
If using C# 9 it is now kinda possible, thanks to the top-level statements feature.
In your executable project, the following syntax is now allowed:
using SomeNamespace;
// The following statements are seemingly defined without even a method,
// but will be placed inside a "Main" static method in a "$Program" static class
SayHello();
var classFromSomeNamespace = new SomeClass(); // from SomeNamespace
classFromSomeNamespace.SomeMethod();
// This function is seemingly defined without a class,
// but on compile time it will end up inside a "$Program" static class
void SayHello()
{
Console.WriteLine("Hello!");
}
// Here the "traditional" syntax may start
namespace SomeNamespace
{
public class SomeClass
{
public void SomeMethod()
{
Console.WriteLine("SomeMethod called");
}
}
}
It should be noted, that the above syntax is valid only for a single file in a project, and the compiler actually still wraps this all inside a $Program static class with static methods. This feature was introduced specifically to avoid boilerplate code for the program entry point, and make it possible to easily write "scripts" in C#, while retaining the full .NET capabilities.
There is no concept of standalone functions in C#. Everything is an object.
You can create static methods on some utility class, and call those without creating an instance of a class eg
class Program
{
static void Main()
{
House.said();
}
}
public class House
{
public static void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
You have to put them in a class, but the class can be static as others mentioned. If you REALLY want to have a separate file for each method, you can mark the class as partial to get the following:
Program.cs
----------
class Program
{
static void Main()
{
House.said();
House.saidAgain();
}
}
House-said.cs
-------------
public static partial class House
{
public static void said()
{
Console.Write("fatty");
Console.ReadLine();
}
}
House-saidAgain.cs
------------------
public static partial class House
{
public static void saidAgain()
{
Console.Write("fattyAgain");
Console.ReadLine();
}
}
I wouldn't recommend separating each one out, however. Partial classes are mostly used so that designer-generated code won't overwrite any custom code in the same class. Otherwise you can easily end up with hundreds of files and no easy way to move from one method to another. If you think you need a partial class because the number of methods is getting unmaintainable, then you probably need to separate the logic into another class instead.
Although the concept of stand-alone functions exists in .NET, C# doesn't allow you to specify such functions. You need to stick them inside a static Utils class or similar.
If you declare your method as static (that is: public static void said()) then you can just call it with House.said(), which is as close as you'll get in C#.
You could add all your methods to the Program class, but this would quickly become an unmaintainable mess, commonly referred to as the God Class or Ball of Mud anti-pattern.
Maintaining a single file for each function would similarly become a huge mess. The questions "Where do I put my methods" and "What classes should I create" are answered by Design Patterns. Classes aggregate behavior (functions) and should do one thing (Single Reponsibility.)

c# : console application - static methods

why in C#, console application, in "program" class , which is default, all methods have to be static along with
static void Main(string[] args)
Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.
With static methods:
public class Program
{
public static void Main()
{
System.Console.WriteLine(Program.Foo());
}
public static string Foo()
{
return "Foo";
}
}
Without static methods (in other words, requiring you to instantiate Program):
public class Program
{
public static void Main()
{
System.Console.WriteLine(new Program().Foo());
}
public string Foo() // notice this is NOT static anymore
{
return "Foo";
}
}
Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.
You can write non static methods too, just you should use like this
static void Main(string[] args)
{
Program p = new Program();
p.NonStaticMethod();
}
The only requirement for C# application is that the executable assembly should have one static main method in any class in the assembly!
The Main method is static because it's the code entry point to the assembly. There is no instance of any object at first, only the class template loaded in memory and its static members including the Main entry point static method. Main is predefined by the C# compiler to be the entry point.
A static method can only call other static methods (unless there is an instance handle of something composited for use). This is why the Main method calls other static methods and why you get a compile error if you try to call a non-static (instance) method.
However, if you create an instance of any class, even of the Program class itself, then you start creating objects in your application on the heap area of memory. You can then start calling their instance members.
Not all methods have to be static, you can add instance methods and also create an instance of your Program class.
But for Main it has to be static beacause it's the entry point of your application and nobody is going to create an instance and call it.
So, technically correct answers are above :)
I should point out that generally you don't want to go in the direction of all static methods. Create an object, like windows form, a controller for it and go towards object-oriented code instead on procedural.

Categories

Resources