C# - How to make programs without IDE/Visual Studio? [closed]

佐手、 提交于 2019-12-02 07:01:24

Nice to see someone starting so simple. Object references are the same no matter if you are working in VisualStudio, or in a simple text editor.

This is actually an error in your code and not the fact that you are not using an IDE.

I'm assuming you have not gone into object oriented programming too much, and that these are simple, single class programs to help you get started.

In this case, all other methods, fields, etc, are accessed in some way from your public static Main(string[] args) method. Static methods are accessible from all classes, and do not require an object instance. Methods and fields accessed without an instance must be static.

So, in this case, yes, every method does need to be static.

Check out this question, What's a "static method"?

For example, say you create a class called Math, and create a Pow(int x, int power) (power) method (This is part of the .NET framework). You would make this function static because you want ALL classes to be able to access it without creating an instance of the Math class.

int square = Math.Pow(2, 2); //Static method, no instance needed

Now say, you make a class called Book, this class has methods such as GetPagesLeft(). In this case, it is specific to each instance of a "book", and should not be static, because it applies to each instance.

Book book = new Book(); //Create instance
int pagesLeft = book.GetPagesLeft(); //Instance method

Don't be afraid of using static methods, they are there for a reason.

Note, I'm not a professional developer, so some of the terminology I used may not be exactly correct, but I hope it gets the point across.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // instanceMethod();  // Error calling instance method without an instance.
                                  // Won't even compile


            Program prg = new Program();
            prg.instanceMethod(); // No Error calling instance method from instance

            staticMethod(); // No Error calling static method without an instance
        }

    void instanceMethod()
    {

    }

    static void staticMethod() 
    {

    }
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!