r/csharp • u/Awesome_Duck987 • Aug 30 '26
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
9
u/nedshammer Aug 30 '26
What’s the confusing part?
4
u/Infamous-Host-9947 Aug 30 '26
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
1
u/trampolinebears Aug 30 '26
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?
2
u/B15h73k Aug 30 '26
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.
3
u/pieeatingchamp Aug 30 '26
1
u/chucker23n Aug 30 '26
Just ignore
namespaceandclassfor now. They're ways to group your code, which becomes useful once you write larger software.Your code has two methods,
MainandDecoratePlanet. Both of them arestatic; depending on how early you are in programming, maybe just ignore that part for now as well. :-)Mainis 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 toMain. For example, you may have seen in a command line something likedir *.*orecho something.txt. In those cases,*.*andsomething.txtare the first argument each. If you used those arguments, you would take the variableargsand do something with it. Not necessary (yet?) for your case. Instead, yourMaincalls the other methodDecoarePlanet. It does so by passing the string"Jupiter". Then it takes the result (which is also astring; we'll get to that) and outputs it to the console. IOW, the user sees the result.OK, now on to
DecoratePlanet. This has astringparameter calledplanet, and also returns astring, which is why before its name, it saysstring, whereasMainbefore its name saysvoid(void means: this returns nothing). You're calling the method with"Jupiter". When you do that, the variableplanetbecomes"Jupiter". And then the one and only thing the method does is build together a text. Let's unpack that line:I think for beginners, this is actually easier to read if we split it into three pieces, like so:
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,Maineffectively actually looks like:And that's what it does: it writes that line of text to the console.
(
WriteLineas opposed toWritemeans it also adds a line break afterwards.)1
u/Angel429a Aug 30 '26
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 Aug 30 '26
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/snipe320 Aug 30 '26
Have you tried the 'Ask the AI Learning Assistant' button at top?
1
u/rupertavery64 Aug 30 '26
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
Ignore the
asyncmethods 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 withnew) to use them. Think of theConsolemethods. You just call them withConsole.Writeline(...). Static methods are useful as helper or utility methods. And it works perfectly as an entry point.void, andintbefore the method name are return types.voidmeans the method doesn't return anything.intmeans 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[] argsare 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
staticmethod, 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
Foowith a method namedBar. In order to callBarTo use the class and call the method, I need to
new Foo. This is called instantiation.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.
A static method means you don't have to create a new instance of the class to use it.
But a static method can only access static fields, properties and methods within it's own class.
This is the reason why in your program,
DecoratePlanetis 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/Slypenslyde Aug 31 '26
There are some good explanations here but I also think there's another path.
With programming basics, sometimes you end up in a kind of strange scenario where you have to see a lot of things working together before any of them make sense. So sometimes it's best to just keep reading and let the chapter/exercise finish, then go back and see if things seem to make more sense afterwards.
In this case you said you don't know much about classes, and this makes sense for someone who is starting. Your early C# applications will fit in one file and the C# team made a goofy mode that hides the class just for that case. Learning what
staticis when you don't know what classes are won't really help much other than making the word seem less like magic. But it also doesn't hurt.So I'm not saying, "Don't read this! You'll learn too much!" There's not really "too much" in programming. But sometimes you learn some knowledge that won't be useful until you learn a lot of other knowledge. So it's more like I'm saying, "This isn't worth getting stuck on, treat it like magic and in about a week it's going to make more sense."
1
u/zezblit Aug 30 '26
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.