These days I am just doing some brainstorming on OOPS and suddenly one question came to my mind. I find it relevant so, I decided to ask the community.Question is:

Static constructor cannot have return type(int,string etc) but static method must have return type in C#.

How does c# compiler distinguish both the situation to get it passed through compilation?

static Class staticClass
{
    public static staticClass(){} //right

    public static int staticClass(){} //wrong

    public static int staticMethod(){} //right
}
有帮助吗?

解决方案

Static constructor cannot have return type(int,string etc)

Correct. But a (static) constructor does not need to return anything.

but static method must have return type in C#.

Wrong. A static method can very well be a void method.

How does c# compiler distinguish ...

static class StaticClass
{
  public static StaticClass(){} //right  : Wrong. 'public' is not allowed.

  public static int StaticClass(){} //wrong : Indeed wrong. Member cannot have same name as class

  public static int StaticMethod(){} //right
}

其他提示

Static constructor is type of Constructor means there will not be any return type reason it call during fist class object initialization. But Static method is method which call with the name of class. Suppose you have a class A , you have a method static string display() then you can call A.display(). because static method is common to all the object of a class. To know more about Constructor and his type check This URL constructors-net-using-csharp-singleton-pattern/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top