AliTeo AliTeo - 1 month ago 6
C# Question

Is this a constructor declaration?

I am new to C# language and came across this kind of declaration in a website. I haven't seen this type of constructor(?) before, so I was really confused:

public class Employee {

public string Name { get; set; }
public string Title { get; set; }

public static Employee GetEmployee() { //Constructor? Method?
var emp = new Employee() {
Name = "Somebody", Title = "Developer"
};
return emp; //Returns to a method?


Thanks a lot.

Answer
//Constructor? Method?

Method. A static method.

This pattern is commonly used in conjunction with a private constructor:

public static Employee GetEmployee()
{
    return new Employee()
    { 
        Name = "Somebody", Title = "Developer" 
    }; 
}

private Employee() { }

The private constructor ensures that an instance of the class can only be created by using one of the static methods.

Such a "factory method" is more flexible than a constructor:

  • It can return an instance of a subclass (often used with private, inner subclasses),
  • it has a name, which can increase readability and allows you to have multiple factory methods with the same parameter list but different names (such as GetDeveloper() and GetManager()).

However, it also has a drawback: You can only set readonly fields in a constructor. Thus, if Employee were an immutable class with readonly fields, you'd need to pass all values to the private constructor when using this pattern.

Comments