Question

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
}
Was it helpful?

Solution

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
}

OTHER TIPS

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top