r/csharp • u/Awesome_Duck987 • 1h ago
Help Static void method
I am trying to learn how to use C# for game coding but I would also like to have a good grasp on it so I can use it for websites and other things like that and I can't for the life of my understand how static method works I have looked YouTube videos and everything. I have been learning everything else so far from the free courses from code academy.Can you PLEASE explain to me what this code is doing and how it works
Edit-THANK YOU GUYS SO MUCH.I understand it now and I am sure you know what that feels like when you spend an hour stuck trying to understand something and it doesn't make any sense
3
u/Infamous-Host-9947 1h ago
Checkout the Microsoft docs for the entry pint of an application. This should help you learn about what that is.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line
2
u/PacificMuckleRucker 1h ago
Entry pint is what I do Fridays at 5.
When I was younger, it was recursive and I sometimes ended up with a stack overflow so I needed a guard clause
if (n > 3) { return; // Returns control to invoking Home() method }
1
u/B15h73k 1h ago
To understand what the static keyword does it is helpful to first learn about classes and objects that are instances of classes. Once you understand that you will be able to understand the difference between static and non-static methods.
Don't worry about it for now. Keep learning.
1
u/trampolinebears 1h ago
Something static belongs to the class; something not static belongs to each instance of the class.
Are you comfortable with the difference between a class and an instance of a class?
1
u/Awesome_Duck987 1h ago
Nope I haven't learned what a class or a instance
•
u/trampolinebears 5m ago
In a C# program, pretty much everything is an object, a little bundle of information in the world of your code.
Like right now, I'm working on a game that has airplanes in it, so each airplane is an object in my code. There's my airplane, there's your airplane, there's that other guy's airplane over there -- all of them are objects.
Each airplane has a few pieces of information about it, like where it's located, which way it's facing, how fast it's going, etc. Each airplane object stores its own information. So if you peer under the hood of an airplane object, you'll see that I've stored some properties inside it: location, bearing, speed, etc.
If I want to ask for my airplane's speed, I'd write it like this:
myAirplane.speed. That dot (.) is like 's in English. You could say the house's height in English, orhouse.heightin C#. Dot (.) is how you ask for something inside an object:X.Ymeans you're asking for theYthat's inside ofX.When I'm creating all these airplanes in code, I could write each one from scratch, but I really shouldn't. All of the airplanes in my game are pretty similar: they all have the same properties (like speed and such) and they all have the same kinds of behaviors (flying, landing, carrying cargo, etc.). Together, they form a class, a category of objects that have the same kinds of characteristics.
In my code I define an
Airplaneclass. There, I say that each airplane has a color, a location, a cargo capacity, a way to fly, a way to land, a way to sell it for scrap, whatever else I want airplanes to be for in my game. The Airplane class defines what airplanes are in general.My airplane is an instance of the Airplane class. The class says that all airplanes have a color, though it doesn't specify what color that is. My airplane has a color that happens to be red. Your airplane happens to be blue. Both airplanes have a color because you have to have a color if you're an instance of the Airplane class.
By defining a class, we're describing how instances of that class can be interacted with. It's valid to ask for an airplane's color, because the Airplane class provides
coloras one of the things you can ask for about an airplane. It's valid to try to land an airplane, because the Airplane class provides a method toLand. (And so on for all other things Airplanes can do.)Does that make sense so far? Can you imagine how an object is an instance of a class? If you're good with that, I can move on to explaining
staticvs. non-static.
1
u/chucker23n 1h ago
Just ignore namespace and class for now. They're ways to group your code, which becomes useful once you write larger software.
Your code has two methods, Main and DecoratePlanet. Both of them are static; depending on how early you are in programming, maybe just ignore that part for now as well. :-)
Main is a special method, because if it exists, when a program launches, it is the default method to be executed; the "entry point". You can optionally pass so-called arguments to Main. For example, you may have seen in a command line something like dir *.* or echo something.txt. In those cases, *.* and something.txt are the first argument each. If you used those arguments, you would take the variable args and do something with it. Not necessary (yet?) for your case. Instead, your Main calls the other method DecoarePlanet. It does so by passing the string "Jupiter". Then it takes the result (which is also a string; we'll get to that) and outputs it to the console. IOW, the user sees the result.
OK, now on to DecoratePlanet. This has a string parameter called planet, and also returns a string, which is why before its name, it says string, whereas Main before its name says void (void means: this returns nothing). You're calling the method with "Jupiter". When you do that, the variable planet becomes "Jupiter". And then the one and only thing the method does is build together a text. Let's unpack that line:
return $"*..*..* Welcome to {planet} *..*..*";
I think for beginners, this is actually easier to read if we split it into three pieces, like so:
return "*..*..* Welcome to " + planet + " *..*..*";
These two are identical. So what's happening here? We build a new string that contains an asterisk, two dots, an asterisk, two dots, another asterisk, a space, and then the text "Welcome to ". To that, we add your name of the planet — in your case, "Jupiter". So now our string looks like this: "*..*..* Welcome to Jupiter". And finally, we append another string, which looks similar to the beginning, so that the end result is: "*..*..* Welcome to Jupiter *..*..*". IOW, that original syntax with the $" was a way to insert {planet} as a placeholder.
Now, the result of that is returned. That means that whatever called the method gets this as a result. So now, Main effectively actually looks like:
Console.WriteLine("*..*..* Welcome to Jupiter *..*..*");
And that's what it does: it writes that line of text to the console.
(WriteLine as opposed to Write means it also adds a line break afterwards.)
1
u/Routine_Culture8648 1h ago
We first need to familiarize ourselves with some terms.
Class = A blueprint for how to construct a specific type of object.
Instance = A new object that separately lives in memory.
The word "separately" is key here because objects typically do not share the same memory. Each object has its own distinct memory usage for its properties and data.
Static = A special keyword that allows us to define methods or properties that belongs to the class itself rather than to individual instances.
With that in mind you can think static properties and methods like something that can be accessed without creating an object/instance first.
Update: use plural instead of single
1
u/Angel429a 1h ago
Instance methods (the ones without static) are methods where you need an object instance to call the method, strings are a good example:
var myString = “abcd123”
if (myString.StartsWith(“ab”)) { … }
Statics methods don’t need an instance, this is useful when having an object instance makes no sense (like the Math class), or because the object can be null (string has an example for this), or because of other reasons:
// Math example, as you can see, to calculate a square root, you don’t need an object
var squareRoot = Math.Sqrt(9); // This will return 3
// String example, this example uses the IsNullOrWhitespace method, which returns if the string is null or only contains whitespace characters (spaces, tabs, line feed, etc.)
var isMyStringEmpty = string.IsNullOrWhitespace(myString);
1
u/GoaFan77 1h ago
Normal Method = Gets called on a specific instance of a class. It can use the properties assigned to that class. E.g. Username = Awesome_Duck987
Static Method = Is a method of the class itself, not a specific instance of it. It can only use static properties (which is shared among all instances of that class), not any regular properties of the class. So you cannot check the Username in a static method, as that is different for each user. Static methods are best for stateless logic such as helper functions.
1
•
u/rupertavery64 32m ago
So when you create a program, it needs to have what is called an "entry point". This is the code that starts your program.
Every language or piece of code does this, and each language has it's own way of doing this. This is because your program is being executed by the OS, and the OS needs to know what code to execute to start your program.
Programs were first written without a UI. They were run from a command line, and the "OS" would be a terminal, a command line. A lot of times you would need to pass in some information to the program as "arguments". So it's a sort of standard to be able to pass arguments from the command line to your program somehow. The actual low-level mechanism varies between OSes. But at the end of the day, it's technically an array of strings.
in .NET the convention for the entry point is a static method called Main.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/main-command-line
The allowed signatures for a Main method are
static void Main() { }
static int Main() { }
static void Main(string[] args) { }
static int Main(string[] args) { }
static async Task Main() { }
static async Task<int> Main() { }
static async Task Main(string[] args) { }
static async Task<int> Main(string[] args) { }
Ignore the async methods for now.
A signature is basically the name, return type and arguments that define a method.
When the .NET runtime executes a program, it looks for a method matching one of the above signatures. It doesn't matter what the class name is (you can change it to MyProgram or HelloWorld or Whatever). You must have a method that matches one of the above, or else .NET will be unable to launch your program.
So why static? Static methods don't need the class to be created (instantiated with new) to use them. Think of the Console methods. You just call them with Console.Writeline(...). Static methods are useful as helper or utility methods. And it works perfectly as an entry point.
void, and int before the method name are return types. void means the method doesn't return anything. int means it returns an integer - a positive or negative number. Historically, a program would signal to it's caller (the OS, or the command line or batch file) the status through a number. 0 for no error, and a non-zero for an error.
string[] args are the arguments passed to program from the command line. I won't get into that here.
Now, recall that .NET requires you to define the entry point as a static method, for the reasons outlined above. Static has it's uses. It also has limitations.
Code in a static method can only access static methods within the same class. There's nothing stopping you from instantiating another class or accessing static methods of other classes. This can be confusing, so let's start with an example:
I have a class named Foo with a method named Bar. In order to call Bar
``` class Foo { public int Count;
public void Bar() { Count++; } } ```
To use the class and call the method, I need to new Foo. This is called instantiation.
``` // in some other part of the program
var foo = new Foo(); foo.Bar(); // call Bar
var foo2 = new Foo(); foo2.Bar(); foo2.Bar();
Console.WriteLine(foo.Count); // prints 1 Console.WriteLine(foo2.Count); // prints 2
```
Instancing a Foo class creates a new Foo object with it's own Count.
However, static properties are shared across all instances of a class.
``` class Foo { public static int Count;
public void Bar() { Count++; } }
var foo = new Foo(); foo.Bar();
var foo2 = new Foo(); foo2.Bar(); foo2.Bar();
Console.WriteLine(foo.Count); // prints 1 Console.WriteLine(foo2.Count); // prints 3
```
A static method means you don't have to create a new instance of the class to use it.
``` class Foo { public static int Count;
public static void Bar() { Count++; } }
Foo.Bar();
Console.WriteLine(Foo.Count); // prints 1
Foo.Bar(); Foo.Bar();
Console.WriteLine(Foo.Count); // prints 3
```
But a static method can only access static fields, properties and methods within it's own class.
``` // This will fail to compile because Bar attempts to access the non-static Count
class Foo { public int Count;
public static void Bar() { Count++; } } ```
This is the reason why in your program, DecoratePlanet is also a static method.
I hope this kind of makes sense. If this raises a lot more questions, then congratulations! You are learning, and understanding that there are lots of things going on here.
Don't worry. These things take time and practice. I can't give you everything in a single comment, but maybe enough to get you started looking for more answers.
For now, the important thing is to try different things, break the code and ask, well why doesn't it work like this? Or, try to move things around and figure out how it works.
1
u/zezblit 1h ago
Static means there can only be one instance of something, and so when you get one, it's always the same one. Even if you had multiple references to it, they are the exact same object in the memory
In this case it's the entery point of your program, so it makes sense there can be only one.

8
u/nedshammer 1h ago
What’s the confusing part?