vbp13
vbp13

Reputation: 1180

Enforce Class Only Exists as part of 1 other class

I have a class that I want to be a property of another class. However, I only want this one other class to be able to have a property of that 2nd class.

I thought I would create a nested private class. However, doing that, gives me compiler error: "Inconsistent accessibility"

class OuterClass
{
    public InnerClass MyInnerClass { get; set; }


    private class InnerClass
    {
        public bool CanItBe { get; set; }
    }
}

class DifferentClass
{
    public InnerClass IWantThisToNotBePossible { get; set; }
}

Update: Problem trying to solve

Class Bicycle
{
    public WheelSettings MyWheelSettings {get;set;}
}

Class WheelSettings
{
    public decimal SpokeLength {get;set;}
}

Class SteeringWheel 
{
    public WheelSettings MyWheelSettings {get;set;} ==> i want this to be 
    an error -> WheelSettings class cannot be used in any class other than 
    Bicycle
}

Upvotes: 0

Views: 835

Answers (1)

markonius
markonius

Reputation: 657

This cannot be done. If your class exposes a property or method returning WheelSettings, the class needs to be public, so that any other class can see that it exists and know what's inside of it.
By rules of C#, this means any code that can see this class exists can hold a reference to it. It can be a local variable, a field, or returned by a method.

If you really want to prevent anyone from misunderstanding the purpose of your class, you can make a public interface.

public class Bicycle {
   public IWheelSettings MyWheelSettings { get; set; } = new WheelSettings();

   public interface IWheelSettings {
      decimal SpokeLength { get; set; }
   }

   private class WheelSettings : IWheelSettings {
      public decimal SpokeLength { get; set; }
   }
}

This way you can prevent anyone instantiating instances of IWheelSettings, since no class that implements it is publicly known.
Of course, nothing is preventing me from implementing it myself.

BTW, any other class would need to qualify WheelSettings with Bycicle anyway, so it's pretty obvious that it shouldn't be used in other context already.

public class Car {
    public Bicycle.WheelSettings settings;
}

EDIT: Also, consider this: If instances of WheelSettings should never be referenced without the Bicycle, why does it exist? Why aren't wheel settings properties of the Bicycle itself?

Upvotes: 2

Related Questions