I’m not really sure what to call this, because “static constructor” seems to convey the concept of static initializer blocks, but my question has to do with style.
Let’s say I have a class Weapon that has your standard constructors for initializing a weapon’s stats. This works fine, but sometimes I want to randomly generate a weapon. I could create a static method called FromRandom which creates a new Weapon with random stats and returns it. That way I could do something like this:
Weapon randWeapon = Weapon.FromRandom();
What’s the consensus on this? Is this acceptable code?
Giving a class static methods that give you more control and gracefulness by returning instances of the class they are in is perfectly acceptable code. This is actually called the factory method pattern and is used quite often when you greater control when an instance of a class is created.
Basically, you have the static method call one of the class constructors, do whatever it needs to do in terms of logging the creation of the object, adding it to a collection, performing further operations on it, etc., and then return the created object, so the method ends up being used like a normal constructor. 😀