I code in c#, as I understand, inside the Program class, there is the static Main, when I want to create a new method inside Program and reference it in Main it must be static, meanwhile, if I make a custom class, the methods inside the class are not required to be static to have a reference in the class. Is there a specific reason or just syntax?
Asked
Active
Viewed 61 times
0
-
1You can call nonstatic methods defined in Program from Main, you just need an instance of Program to call them from (i.e. `new Program().MyNonStaticMethod()`). But that's probably not what you're actually trying to do as it would be a bit odd. Do you have a practical example where you think you need to do this? – Broots Waymb Jun 03 '22 at 20:48
-
2This dupe doesn't seem right.. OP is asking about methods needing to be static to call them from Main, not asking why Main itself is static. – Code Stranger Jun 03 '22 at 20:50
-
@CodeStranger I think it is more charitable interpretation of the question. The way you read it sounds rude to me: "Why can't I call instance methods when I don't have an instance to call the method on"... – Alexei Levenkov Jun 03 '22 at 21:44
-
1I suggest you try this as an experiment:. Create another class, add a static method to it and a non-static method. Try to call the non-static method from the static method. You'll get the same error as when you tried to call a non static method from Program.Main. In order to invoke a non-static method (sometimes called an instance method), you must have an instance of that object. Doesn't matter whether it's Program or any other class, they all behave the same. – mason Jun 03 '22 at 21:55
-
In the beginning, all methods were "static." The real question is why do we need anything else? The answer to that will become clearer to you as you learn object-oriented programming. – John Wu Jun 03 '22 at 22:02
-
Thanks for all of your comments, but what I meant is more like, let's say we have a class, inside the class, there is a method called "DoSomething", and we have a constructor, so inside the constructor we can call the method like this: DoSomething(); but if we make the same method inside the Program class(generated one), and try to call it in Main(entry) then we'll get an error because it is not being "detected", but if we add static for example, static void DoSomething(), then if we call DoSomething(); in main it will be "detected". My question is why static is needed if it's under Program. – Weebeveloper Jun 04 '22 at 22:12