Search code examples
c#partial-classes

Using partial classes to add private properties?


I have a public class I'm defining that will eventually be part of an API, so it has to have certain public properties. However, I also want some of the properties to be read-only unless they're created from within my own projects (e.g., if a user has our API, they can create a User object, but they can't write to its ID field, which will be filled in only if we pull it from the database).

My thought was to have two separate assemblies using the same namespace, the "public" DLL and the "private" DLL. The prototype in the public DLL will look like:

namespace CompanyName
{
  public partial class User
  {
    public Id { get; }
    public Name { get; set; }
  }
}

and the private DLL will have this:

namespace CompanyName
{
  public partial class User
  {
    public Id { set; }
  }
}

Would this work? If not, what's a better way to do this?


Solution

  • Partial classes cannot span assemblies, so this will not work.

    You could define your class as:

    namespace CompanyName
    {
        public class User
        {
            public Id {get;internal set;}
            public Name {get;set;}
        }
    }
    

    This would mean that only code with internal access to your class could set the value of Id property. If you need to set it from outside your assembly, make sure your assemblies are strong-named and you can then use the InternalsVisibleTo attribute to give internal access to your assembly to another one of your assemblies (the one setting the value of Id).


    I've recently had to do something very similar to this for an API I work on. Our API is defined mainly using interfaces, so I was able to achieve this by having a Public API project that is the public part, and an Internal API project that forms the API used by our internal code, with internal interfaces deriving from the public ones. The implementations of the API interfaces implement both interfaces, meaning our internal code can then access parts of the API that are not public.