Ankur Bhutani Ankur Bhutani - 2 months ago 8
C# Question

Static constructor cannot have return type but static method must have return type in C#

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
}

Answer

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
}
Comments