开发者

Why you can create class self intance in class's main method

Why you can do this in C#?

class Test
{
    static void Main()
开发者_运维问答    {
        Test test = new Test();            
    }
}


You can create new instances of any non abstract, non static class including your own where ever you can write code ...

Test is not a static class, even if it does not have any non-static methods. It always gets a default constructor if there isn't defined any. So you can call it.

class Foo
{
}

static class Bar
{
   static void Baz()
   {
     // you can create an instance of class Foo
     Foo f = new Foo();
   }
}


Why wouldn't you be able to? Main() is a static method. (Edit: And anyway, you can create new instances of non-abstract, non-static classes almost anywhere. See Stefan Steinegger's comment and answer.)


You can do this, because Main is static. It runs without any instance whatsovever. So, elsewhere in the code you could call Test.Main directly without having to create an instance of it.


Why not? I just tried it and it works


A real-world application of this behaviour is the Singleton Pattern. Now that you know about it - don't use it ;)


Why would you do this?

A well-designed object-oriented program is a graph of objects and sub-objects. However, entry points to programs are typically very procedural. Creating an instance of a root object (which then creates sub-objects, etc.) is a good way to bootstrap your object graph.

This is why you see things like Application.Run(new MyClass()); in static main methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜