Why its possible to override explicit implementation? - c#

We usually implement interfaces explicitly when it’s not right to access interface member directly from implementer class. Weather it has to be internal or it causes conflicts with API design or when it increases the chance of misusing methods.
Implementing members individually for multiple interfaces with different logic is absolutely discouraged in my mind so that’s not case here
Compiler does not allow making such implementation as virtual because it doesn't make sense and I think it’s right. Usually explicit implementation is very sensitive and that’s why you try to hide it.
However I found following way of over-riding explicit implementation (it’s not exactly override but its cheating alternative)
I found this surprising and quite disappointing. My question is why following code is allowed and works perfectly? I expected to get error that interface is already implemented explicitly.
This is just basic example to reproduce problem
static void Main(string[] args)
{
var b = new Base();
((IInterface)b).Write();
var c = new Child();
((IInterface)c).Write();
}
public interface IInterface
{
void Write();
}
public class Base : IInterface
{
void IInterface.Write()
{
Console.WriteLine("Base");
}
}
public class Child : Base, IInterface // hack is here. Re Implemented :/
{
void IInterface.Write()
{
Console.WriteLine("Child");
}
}
Outputs
Base
Child

why following code is allowed and works perfectly?
Because the specs say so:
It is a compile-time error for an explicit interface member implementation to include access modifiers, and it is a
compile-time error to include the modifiers abstract, virtual, override, or static.
Yet in polymorphism, the saying goes "the more derived type knows better", from the specs again:
derived classes can extend and specialize base classes
So the most derived type who implements that interface explicitly will be called when you invoke that interface member.

I suggest you to think at the low level translation from C# into native code: the interface inheritance redeclaration, and the one or more of its methods overriding, forces rewriting of the VMT - Virtual Method Table (interface methods are virtual by design).

Related

Can C# mark and check when a class implements interface methods? [duplicate]

This question already has answers here:
Equivalent of Java 1.6 #Override for interfaces in C#
(4 answers)
Closed 8 years ago.
When a base class contains a virtual method, to add a more derived version in a sub class, we have to use override.
AFAICT, this serves two purposes:
We don't accidentally overide a base method
If we mistype the method name when we want to override, we get an error (similar to Java, right?)
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
Obviously the first bullet is rather a non issue, but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use override when implementing an interface method.
That's because interface methods aren't overridden, they're implemented. It's a seemingly trivial semantic difference, but when we're talking about the use of language semantics are pretty important.
but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override
Wouldn't it be a bit misleading? override implies that there's a base class definition being, well, overridden. The MSDN documentation defines it as:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
Interfaces aren't inherited, they're implemented. Again, just semantics, but a pretty important distinction. A class may implement multiple interfaces, the same method may be applied to multiple interface definitions, etc.
Overriding inherited behavior implies:
There is inherited behavior (either with a default implementation in the case of virtual or without in the case of abstract), keeping in mind that C# is a single-inheritance language
The implementation is being overridden (which carries specific distinctions in an inheritance model when the parent class internally invokes that member)
These conditions don't apply to interfaces.
So, when looking at a class implementation, is there any way other than a // comment to indicate that this method implements the method of a certain interface?
Actually, yes. You can explicitly implement an interface. Something like this:
interface IDimensions
{
float Length();
float Width();
}
class Box : IDimensions
{
public float IDimensions.Length()
{
// implementation
}
public float IDimensions.Width()
{
// implementation
}
}
I believe that everything about your concern is summarized by this sentence:
but the overridekeyword would have served as a good simple
documentation and check that the interface methods are actually these
that are marked as override.
Think about what's an interface, and what's an implementer. A class may or may not implement an interface, and can still implement a method with the same signature as an interface. What an interface does is the job of ensuring that some class has the required members to fullfil a contract.
For example, a class Calculator may implement ICalculator and Calculator implements Addition(int, int). But Calculator couldn't implement ICalculator and it could perform an Addition(int, int) anyway.
How do you distinguish both cases? When to use override or not.
Another point: it's nice to implement a class, and fulfill an interface, and stop fulfilling it by just removing it from the class signature after the inheritance colon.
In the other hand, think that the documentation you're looking for is the compiler error telling you that Calculator implements interface ICalculator but it doesn't declare and implement one or more members defined by ICalculator. If the code compiles, you shouldn't care about if a member is of some or other interface. You know that some members are implementations of some interface, because your Calculator signature would look like this: public class Calculator : ICalculator.
Also, there's the case where a implementation member implements it to fulfill more than an interface. What's overriding your implementation? Isn't this more confusing than avoiding override keyword?
Suppose you have these types:
interface ISampleInterface
{
void Method();
}
class A : ISampleInterface
{
public void Method()
{
}
}
class B : A, ISampleInterface
{
void ISampleInterface.Method()
{
}
}
class C : A, ISampleInterface
{
public new void Method()
{
}
}
and use them this way:
ISampleInterface a = new A();
ISampleInterface b = new B();
ISampleInterface c = new C();
a.Method(); // calls A.Method
b.Method(); // calls explicit ISampleInterface.Method
((B)b).Method(); // calls A.Method
c.Method(); // calls C.Method
((A)c).Method(); // calls A.Method
Looks like it is hard to define, which of implementations of Method could be marked as override.

Interface and abstract class protection level methods

I came across a bit of code and am not quite sure why it works or why you'd want to do it this way. I would love it if someone could tear it down for me. I do understand well OOP concepts, I simply have not seen this technique before. Thanks
Here is the example:
public interface IInterface
{
IEnumerable<object> DoSomething();
}
public abstract class MyBase : IInterface
{
protected MyBase()
{
}
IEnumerable<object> IInterface.DoSomething()
{
return DoSomething();
}
protected virtual IEnumerable<object> DoSomething()
{
return new List<object>();
}
}
public class MyClass : MyBase
{
internal MyClass() : base() {}
protected override IEnumerable<object> DoSomething()
{
return new List<object>();
}
}
If you're talking about this line of code:
IEnumerable<object> IInterface.DoSomething()
That's called explicit interface implementation.
That forces consumers to access this method only via the interface,
and not to your class directly.
The above method is not private, it's just not explicitly set as public in code. In fact, with explicit interface implementation, you can't even use access modifiers.
One of the reasons for taking this approach is to force better coding practices. If you're the developer of this class, and you know it should only be accessed via an interface, this is the way to force that to happen.
In C#, explicitly implementing an interface by using a sealed method which does nothing but call a protected virtual method allows derived-classes great flexibility with regard to what they want to do with the interface; the method should be given a name other than the name of the interface method (in the above example, it could perhaps be DoSomething_Prot). Explicit interface implementation makes it impossible for a derived class re-implementation to chain to the base-class implementation, but if the only thing the base-class implementation is doing is chaining to a protected virtual or abstract method, there's no need for a derived class to re-implement the interface. Further, even if the derived class were to re-implement the interface either deliberately or as a result of covariance it would still be able to invoke the "guts" of the base-class implementation using the protected method from the base class.
Putting all the code for the interface implementation in a public virtual method which implicitly implements the interface is better than putting code in an explicit implementation, since derived-class code can generally chain to the private member. Such an approach, however, requires that all derived classes publicly implement the method with the same signature. While it may seem like what one would naturally expect anyway, it isn't always. For example, in the above example a derived class may wish to have its DoSomething method return a type other than IEnumerable<object> (e.g. it might return an IList<Kangaroo>). The method which implements the interfae would still have to return precise type IList<Kangaroo>, but code that knew it was dealing with the derived type could use the return type as an IList<Kangaroo> without a typecast. If the actual code for the method were in a method called DoSomething_Prot(), the derived class could both override DoSomething_Prot and declare a new public IList<Kangaroo> DoSomething(). If the base-class method were called DoSomething(), there would be no way for the derived class to both override it and define a new method with a different return type.
Off the top of my head I'm having trouble of thinking of a practical use for this, but one thing that this accomplishes is that objects of type MyBase or its subclasses do not have a public or internally visible DoSomething() method:
MyClass a = new MyClass();
a.DoSomething(); // Compile error
but the DoSomething() method is visible when the object is used as an IInterface:
void AMethod(IInterface i)
{
i.DoSomething(); // compiles just fine
}
void AnotherMethod(MyBase a)
{
AMethod(a); // as does this
}
Making the non-explicit version protected virtual allows subclasses to override the behavior of the DoSomething() method.
This is a way of implementing a method that cannot be called directly when working with MyBases as MyBases, but can be used when they are being treated as IInterfaces. There's nothing to prevent someone from doing this: ((IInterface)a).DoSomething(); but it seems the hiding is done for semantic reasons.
My take on this is that it is an implementation of the template pattern as described here. Typically you see the template pattern used along with the strategy pattern. In your particular example, users of the IInterface could call the DoSomething
method without regard for how the concrete subclass implemented the method.
This kind of OO programming allows you to take advantage of quite a few other patterns such as the AbstractFactory for creating your concrete subclasses of MyBase which implement IInterface.
The important thing to note is that the two DoSomething methods have nothing to do with each other - they just happen to have the same name.
Basically, you've just got a normal interface that exposes a DoSomething method, so the caller who has a IInterface object can call it. It will then in turn pass the call on to the appropriate implementation of the protected DoSomething method, which can either be from the base class or the derived one.
Explicit implementation like this forces you to code by contract instead of implementation - doesn't really provide any actual protection, just makes it more difficult to accidentally use the wrong type when you declare your variable. They just as easily could have done:
public abstract class MyBase : IInterface {
public virtual IEnumerable<object> DoSomething() {
// blah
}
}
public class MyClass : MyBase {
public override IEnumerable<object> DoSomething() {
// blah
}
}
but that would let you call DoSomething on a variable declared as MyClass or MyBase, which you may not want them to do.

Abstract Method in Non Abstract Class

I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.

Why must methods implementing internal interfaces be public

I am developing an internal class that implements an internal interface.
Can anyone explain why I cannot declare my method as internal, why I am getting the following error: "cannot implement an interface member because it is not public".
I know that I have to declare the method as public, but it makes absolutely no sense to me.
What is the point of declaring a method public if both the interface and the class are internal?
Is it not misleading?
I have read a related question on this site. It is not an exact duplicate, because my class is internal.
Simply put: because that's the way the language designers designed it. Even in internal interfaces, the methods are implicitly public. It does make things simple, but it's a pain in other ways.
If you want a public class where you want to "hide" the use of an internal interface, you could use explicit interface implementation - although that has other drawbacks.
Of course, if your class is internal then it doesn't matter that the methods are public anyway - other assemblies aren't going to be able to call the methods because they can't see the type.
I definitely agree that C# (or .NET in general) hasn't been designed as carefully as it might be around internal interfaces.
In terms of exactly why you're getting an error message - section 13.4.4 of the C# 4 spec (interface mapping) is the reason. Implementations are only found for nonstatic public members and explicit interface member implementations - and if there are any unimplemented members in the interface, an error occurs.
I know this is old but maybe someone find it useful. You can accomplish a kind of internal interface methods like this:
internal interface IFoo
{
void MyMethod();
}
public abstract class Foo : IFoo
{
void IFoo.MyMethod()
{
MyMethod();
}
internal abstract void MyMethod();
}
So all your internal classes should derive from Foo and are forced to implement the abstract MyMethod. But you can treat them all as IFoo of course. But those classes outside the assembly won't provide the MyMethod class.
So you have the advantage to treat your classes internally as IFoo and rely on MyMethod. The drawback is that all your classes will need to derive from Foo which can be a problem if you need another base class.
But I found it helpful if the abstract base class is a generic one and the interface is not. Maybe it is useful in some cases.

C# - Can publicly inherited methods be hidden (e.g. made private to derived class)

Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
public DerivedClass : BaseClass {}
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
It's not possible, why?
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow this on purpose so that you use inheritance more properly.
For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations.
So they don't allow it to protect you from bad inheritance hierarchies.
What should you do instead?
Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship.
Other languages:
In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#.
The restructured code:
interface I
{
void C();
}
class BaseClass
{
public void A() { MessageBox.Show("A"); }
public void B() { MessageBox.Show("B"); }
}
class Derived : I
{
public void C()
{
b.A();
b.B();
}
private BaseClass b;
}
I understand the names of the above classes are a little moot :)
Other suggestions:
Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
When you, for instance, try to inherit from a List<object>, and you want to hide the direct Add(object _ob) member:
// the only way to hide
[Obsolete("This is not supported in this class.", true)]
public new void Add(object _ob)
{
throw NotImplementedException("Don't use!!");
}
It's not really the most preferable solution, but it does the job. Intellisense still accepts, but at compile time you get an error:
error CS0619: 'TestConsole.TestClass.Add(TestConsole.TestObject)' is obsolete: 'This is not supported in this class.'
That sounds like a bad idea. Liskov would not be impressed.
If you don't want consumers of DerivedClass to be able to access methods DeriveClass.A() and DerivedClass.B() I would suggest that DerivedClass should implement some public interface IWhateverMethodCIsAbout and the consumers of DerivedClass should actually be talking to IWhateverMethodCIsAbout and know nothing about the implementation of BaseClass or DerivedClass at all.
What you need is composition not inheritance.
class Plane
{
public Fly() { .. }
public string GetPilot() {...}
}
Now if you need a special kind of Plane, such as one that has PairOfWings = 2 but otherwise does everything a plane can.. You inherit plane. By this you declare that your derivation meets the contract of the base class and can be substituted without blinking wherever a base class is expected. e.g. LogFlight(Plane) would continue to work with a BiPlane instance.
However if you just need the Fly behavior for a new Bird you want to create and are not willing to support the complete base class contract, you compose instead. In this case, refactor the behavior of methods to reuse into a new type Flight. Now create and hold references to this class in both Plane and Bird.
You don't inherit because the Bird does not support the complete base class contract... ( e.g. it cannot provide GetPilot() ).
For the same reason, you cannot reduce the visibility of base class methods when you override.. you can override and make a base private method public in the derivation but not vice versa. e.g. In this example, if I derive a type of Plane "BadPlane" and then override and "Hide" GetPilot() - make it private; a client method LogFlight(Plane p) will work for most Planes but will blow up for "BadPlane" if the implementation of LogFlight happens to need/call GetPilot(). Since all derivations of a base class are expected to be 'substitutable' wherever a base class param is expected, this has to be disallowed.
#Brian R. Bondy pointed me to an interesting article on Hiding through inheritance and the new keyword.
http://msdn.microsoft.com/en-us/library/aa691135(VS.71).aspx
So as workaround I would suggest:
class BaseClass
{
public void A()
{
Console.WriteLine("BaseClass.A");
}
public void B()
{
Console.WriteLine("BaseClass.B");
}
}
class DerivedClass : BaseClass
{
new public void A()
{
throw new NotSupportedException();
}
new public void B()
{
throw new NotSupportedException();
}
public void C()
{
base.A();
base.B();
}
}
This way code like this will throw a NotSupportedException:
DerivedClass d = new DerivedClass();
d.A();
The only way to do this that I know of is to use a Has-A relationship and only implement the functions you want to expose.
Hiding is a pretty slippery slope. The main issues, IMO, are:
It's dependent upon the design-time
declaration type of the instance,
meaning if you do something like
BaseClass obj = new SubClass(), then
call obj.A(), hiding is defeated. BaseClass.A() will be executed.
Hiding can very easily obscure
behavior (or behavior changes) in
the base type. This is obviously
less of a concern when you own both
sides of the equation, or if calling 'base.xxx' is part of your sub-member.
If you actually do own both sides of the base/sub-class equation, then you should be able to devise a more manageable solution than institutionalized hiding/shadowing.
I would say that if you have a codebase that you are wanting to do this with, it is not the best designed code base. It's typically a sign of a class in one level of the heirarchy needing a certain public signature while another class derived from that class doesn't need it.
An upcoming coding paradigm is called "Composition over Inheritance." This plays directly off of the principles of object-oriented development (especially the Single Responsibility Principle and Open/Closed Principle).
Unfortunately, the way a lot of us developers were taught object-orientation, we have formed a habit of immediately thinking about inheritance instead of composition. We tend to have larger classes that have many different responsibilities simply because they might be contained with the same "Real World" object. This can lead to class hierarchies that are 5+ levels deep.
An unfortunate side-effect that developers don't normally think about when dealing with inheritance is that inheritance forms one of the strongest forms of dependencies that you can ever introduce into your code. Your derived class is now strongly dependant on the class it was inherited from. This can make your code more brittle in the long run and lead to confounding problems where changing a certain behavior in a base class breaks derived classes in obscure ways.
One way to break your code up is through interfaces like mentioned in another answer. This is a smart thing to do anyways as you want a class's external dependencies to bind to abstractions, not concrete/derived types. This allows you to change the implementation without changing the interface, all without effecting a line of code in your dependent class.
I would much rather than maintain a system with hundreds/thousands/even more classes that are all small and loosely-coupled, than deal with a system that makes heavy use of polymorphism/inheritance and has fewer classes that are more tightly coupled.
Perhaps the best resource out there on object-oriented development is Robert C. Martin's book, Agile Software Development, Principles, Patterns, and Practices.
If they're defined public in the original class, you cannot override them to be private in your derived class. However, you could make the public method throw an exception and implement your own private function.
Edit: Jorge Ferreira is correct.
While the answer to the question is "no", there is one tip I wish to point out for others arriving here (given that the OP was sort of alluding to assembly access by 3rd parties). When others reference an assembly, Visual Studio should be honoring the following attribute so it will not show in intellisense (hidden, but can STILL be called, so beware):
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
If you had no other choice, you should be able to use new on a method that hides a base type method, return => throw new NotSupportedException();, and combine it with the attribute above.
Another trick depends on NOT inheriting from a base class if possible, where the base has a corresponding interface (such as IList<T> for List<T>). Implementing interfaces "explicitly" will also hide those methods from intellisense on the class type. For example:
public class GoodForNothing: IDisposable
{
void IDisposable.Dispose() { ... }
}
In the case of var obj = new GoodForNothing(), the Dispose() method will not be available on obj. However, it WILL be available to anyone who explicitly type-casts obj to IDisposable.
In addition, you could also wrap a base type instead of inheriting from it, then hide some methods:
public class MyList<T> : IList<T>
{
List<T> _Items = new List<T>();
public T this[int index] => _Items[index];
public int Count => _Items.Count;
public void Add(T item) => _Items.Add(item);
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
void ICollection<T>.Clear() => throw new InvalidOperationException("No you may not!"); // (hidden)
/*...etc...*/
}

Categories