crichavin
crichavin

Reputation: 4572

c# Protected base class only used for inheritance

Struggling a bit with inheritance here. I have common properties to use in two derived classes, so I made a base class LogBaseViewModel. I don't ever want this base class to be used except to be inherited by derived classes, so I made it protected (also tried private).

I found this bit, and maybe I'm mis-interpreting, but thought if I wrapped all 3 of these classes within one, they'd no longer be "outside" and hence this would be allowed.

From section 3.5.3 of the C# 5 specification:

When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it.

However, no joy, I get the error: Error CS0060 Inconsistent accessibility: base class 'LogViewModels.LogBaseViewModel' is less accessible than class 'LogViewModels.LogSearchViewModel'.

public class LogViewModels
{
    protected class LogBaseViewModel
    {
        public int Id { get; set; }
        public string Level { get; set; }
        public string Message { get; set; }
        public string Exception { get; set; }
    }

    public class LogSearchViewModel : LogBaseViewModel
    {

        public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }
    }

    public class LogViewModel : LogBaseViewModel
    {
        public System.DateTime Date { get; set; }
    }
}

Upvotes: 0

Views: 1252

Answers (1)

Sweeper
Sweeper

Reputation: 270790

Applying the protected modifier on LogBaseViewModel would make it accessible only inside LogViewModels, and in subclasses of LogViewModels, not subclasses of LogBaseViewModel.

From here:

A protected member is accessible within its class and by derived class instances.

The "protected member" is the class LogBaseViewModel. "Its class" refers to the enclosing class LogViewModels.

By making LogBaseViewModel protected, you are telling the compiler that you don't want any external class to know about the insides of LogBaseViewModel. But then you said public class LogSearchViewModel : LogBaseViewModel. This allows people to access the insides of LogBaseViewModel through LogSearchViewModel! The compiler sees that this will make the protected modifier on LogBaseViewModel meaningless, so it gives you an error.

You said:

I don't ever want this base class to be used except to be inherited by derived classes.

Which is the use case for an abstract class. You should keep LogBaseViewModel public, and make it abstract.

Upvotes: 4

Related Questions