Search code examples
c#clonestatic-methods

Why isn't a protected setter property available from a static method?


I have a static helper clone method of a specific base type which doesn't allow me to set a base property setter.

public static T Clone<T>(this T source, DomainKey cloneKey)
    where T : DomainObjectWithKey
{
    T clone = source.Clone(); // binary formatter returns object of type T
    clone.Key = cloneKey; // this does not compile
    return (T)clone;
}

public class DomainObjectWithKey
{
    public DomainKey Key { get; protected set; }

The alternative solution was to put the Clone method inside the class itself, which then allowed me to use the protected setter. However, I then have to specify when calling Clone from my derived objects, which seemed pointless.

Therefore my question is, is it due to encapsulation that I can't call the protected setter method from a static method?

Example of the alternative solution but why do I have to specify the type?

category.Clone<Category>(otherCategory.Key); // why do I have to specify <Category> here?

public class Category : DomainObjectWithKey
{
    public long CategoryId { get { return ((IdDomainKey)Key).Id; } }

    public Category(long categoryId)
    {
        Key = new IdDomainKey(categoryId);
    }
}

Solution

I ended up with having a public property so the Key could be accessed from an instance of a derived class but protected internal for the setter which allowed the static helper method to set the property.

public class DomainObjectWithKey
{
    public DomainKey Key { get; protected internal set; }

Solution

  • protected means that it is visible to the subclasses of DomainObjectWithKey. Your Clone method appears to be outside of DomainObjectWithKey.

    Maybe you're looking for internal? internal allows you access to the member from within the same DLL.