Factory pattern in C#: How to ensure an object instance can only be created by a factory class?

You can make the constructor private, and the factory a nested type:

public class BusinessObject
{
    private BusinessObject(string property)
    {
    }

    public class Factory
    {
        public static BusinessObject CreateBusinessObject(string property)
        {
            return new BusinessObject(property);
        }
    }
}

This works because nested types have access to the private members of their enclosing types. I know it’s a bit restrictive, but hopefully it’ll help…

Leave a Comment