Search code examples
c#nuget-packageclass-library

Restrict class from instantiation and encapsulate it in property in another class


Im writing a .net Standard class library and I want to publish it as an internal package,so i have two classes in same project let say as below :

 public class classOne
{

     public void SomeMethod()
        {

        }
}




 public class classTwo
{

     private ClassOne _classOne;

     public classOne clsOne
        {
            get
            {
                lock (padlock)
                {
                    if (_classOne== null)
                        _classOne= new ClassOne ();

                    return _classOne;
                }
            }
        }
}

As you seen above I want the developers to use class one as a property inside classTwo Also I want to prevent the instantiation of classOne. just the only way to call classOne methods is through classTwo "clsOne" property.

    //I want this code
classTwo clsTwo = new classTwo();
clsTwo.clsOne.someMethod();


//And Prevent to do this code
classOne clsOnew= new classOne();
clsOne.someMethod();

how do i implement that ?


Solution

  • If you only care about ClassOne not being instantiated outside of your package, you could make the constructor of ClassOne internal.

    If you only want ClassOne to be instantiated by ClassTwo, you could make a public interface, IClassOne and make ClassOne implement IClassOne and be a private nested class inside ClassTwo.

    public interface IClassOne
    {
        void SomeMethod();
    }
    
    public class ClassTwo
    {
        private ClassOne _classOne;
    
        public IClassOne clsOne
        {
            get
            {
                lock (padlock)
                {
                    if (_classOne== null)
                        _classOne= new ClassOne ();
    
                    return _classOne;
                }
            }
        }
    
        private class ClassOne : IClassOne
        {
            public void SomeMethod()
            {
                // do something
            }
        }
    }