So I am still very new to C# and using interfaces, and when I thought I understood them I realized I don't completely. The confusion I have found that I am seeking some clarification here for is, when you create an interface, and have a class inherit from it
public Interface ISomeInterface
{
//some methods/properties
}
public class FooClass : ISomeInterface
{
//implemented ISomeInterfaces methods/properties
}
And you use this class object in an implementation somewhere in your program
public class BarClass
{
private ISomeInterface _someInterface;
public BarClass(ISomeInterface someInterface)
{
_someInterface = someInterface;
}
//rest of class
}
My confusion is why do I see it setup this way. I thought that I would have instantiated a new object of type FooClass, as well as used an object of type FooClass in the constructor as such:
public class BarClass
{
private FooClass _fooClass;
public BarClass(FooClass fooClass)
{
_fooClass = fooClass;
}
//rest of class
}
What am I missing to understanding this? I didn't think I would directly be declaring objects of an Interface?
Thanks in advance.
The idea is that BarClass should not be tightly coupled to a specific implementation of ISomeInterface.
If you use this:
public BarClass(FooClass fooClass)
it means that the BarClass can work only with this specific FooClass implementation and nothing else. Whereas if you use:
public BarClass(ISomeInterface fooClass)
now the BarClass is no longer tightly coupled to FooClass. This means that the consumer of the BarClass can now pass any implementation of the interface he wants as long as it respects the defined contract (interface). So if he wants FooClass he passes an instance of FooClass, but if he is not satisfied with FooClass he can write his own implementation and pass it to the constructor and from the point of view of the BarClass this is absolutely transparent (it doesn't need to be modified).
The weak coupling between your classes is one of the most fundamental aspects of OOP as it allows you to easily replace one component with another without having to rewrite your entire application.
Suppose FooClass wrote something to a database. You'd like to test BarClass without having to actually set up a database. If you created a different TestFoo that implemented the same interface, you could pretend to be the database and more easily test your class; BarClass wouldn't have to know that it wasn't talking to the 'real' FooClass.
Do you have a C/C++ background? Then you should be aware that
private ISomeInterface _someInterface;
would be written as
private:
ISomeInterface& _someInterface;
In C++ (assuming you have an abstract base class called ISomeInterface).
This means you are storing a reference to an object implementing ISomeInterface not such an object itself. The advantage of this is that you can pass ANY object to BarClass that implements ISomeInterface which gives you more flexibility, e.g. for unit testing.
By using the interface definition instead of the concrete implementation, your code is now more loosely coupled. This technique is used in dependency injection.
In addition, this comes in handy when you need to need to implement FooClass differently. If you used the concrete implementation, you will need to make code changes where ever you have declared FooClass. Programming against the interface shields you from the effects of such changes.
One of the main benefit to program to ISomeInterface instead of FooClass, is that you might probably change your implementation of FooClass. For example, consider a database driven blog application:
interface IBlogStorage{
getPosts();
}
you then have a class like:
class XMLBlogSotrage: IBlogStorage{}
and suppose you implement everything to the interface. later on, you think XML is too slow and you want to use RDBMS, then:
class MsSQLBlogStorage:IBlogStorage{}
In this case, you don't need to change anything in other codes, you just need to create a new class and plug it in! Those already existed codes, doesn't need to bother where is the storage.
Another way of thinking about the interplay between interfaces and classes is to flip them upside down. That means to start with classes first. Let's say you have several classes that expose a method called "Sort()". Then you have another class that has a method that requires references to these classes and in turn calls their "Sort()" methods. Instead of having several methods with different parameters, you can create and attach an interface to those classes (very quick fix as these classes already contain the implementation).
A.Sort()
B.Sort()
C.Sort()
interface ISortable {void Sort();}
A : ISortable
B : ISortable
C : ISortable
D.SortSomething(ISortable foo)
{
foo.Sort()
}
Maybe this is too abstract. My favorite use of interfaces is enabling my classes to participate in foreach loops.
class SomeCollection : IEnumerable
{
List<SomeItem> _items = new List<SomeItem>();
// This is the only code I need to enable this class to participate in foreach loop.
public Enumerator GetEnumerator()
{
return _items.GetEnumerator();
}
}
Once you discover how interfaces can simplify your codes, you can even begin creating interfaces before writing your classes.
Related
Not very clear with OOP concepts, could be a silly question, please ignore the silliness of it :-)
The question is related to the class below. There I have added a public method "TestMethod()", which is not defined in the interface (below).
Is it a bad practice? Should all methods must be defined in Interface?
In which cases am I allowed to implement a public methods/members in a class, but not in an Interface?
The Interface...
public interface IAnimals
{
void MakeNoise(string noise);
void Move();
string Color
{
get;
set;
}
}
The Class Implementation...
class Animal : IAnimals
{
private string color;
string IAnimals.Color
{
get
{
return color;
}
set
{
color = value;
}
}
void IAnimals.MakeNoise(string noise)
{
Console.WriteLine("Animal " + noise);
}
void IAnimals.Move()
{
Console.WriteLine("Animal moves");
}
public void TestMethod()
{
Console.WriteLine("test method in Animal class");
}
}
The Program...
class Program
{
static void Main(string[] args)
{
//Animal1 show methods and properties defined in the Interface
IAnimals animal1 = new Animal();
//Animal2 only shows the public method of Animal class
Animal animal2 = new Animal();
animal1.Color = "Red";
Console.WriteLine("Animal's color is " + animal1.Color);
animal1.MakeNoise("Barks");
animal1.Move();
animal2.TestMethod();
Console.ReadLine();
}
}
And The Output...
Animal's color is Red
Animal Barks
Animal moves
test method in Animal class
My approach would go something like this.
A class should aim to have one responsibility (Single Responsibility Principle), and its public contract (namely, publicly accessible members) should be relevant to the responsibility it fulfils.
I would not attempt to enforce a correlation between concrete class public members and interface public members. A class may have a public member in order to fulfil a cross-cutting concern that isn't pertinent to the interface contract it is implementing, but is entirely pertinent to the implementation detail. Or it may even be implementing multiple interfaces or some that don't mean anything to its responsibility (such as IDisposable).
It depends on how you expose this contract as to whether this is a potential issue or not. I tend to expose interfaces to offer behaviour, as it allows me to use DI containers etc to manage implementation configurations, which in turn allows me to either mock the interface or provide a test implementation for the purposes of unit testing. That said, if you are handing around concrete types (which are also valid "contracts") then the public face of that type forms an implied contract, so you need to be careful of changing that (just as you would be careful changing interface definitions).
I never particularly worry that I have a type that has more public members than the interface does, but I do try to pay attention to what the type is trying to do (and look out for when it is trying to do too much).
So I would answer that it is good practice to review what responsibilities a class is trying to cover and attempt to minimise that to one, but I would say this public member comparison isn't a relevant "code smell" alert, in my opinion.
The interface definition declares only the properties and methods that makes the implementation comply with the 'contract'.
You will almost never have only the properties and methods defined in the interface in your class, since the class usually needs some more that a general contract implementation.
A good example in a class definition that deviates from the interface is a class implementing ICloneable. You need to implement the Clone method, but that doesn't describe what the class actually does, it just implements that contract the class has with the interface.
In some cases, a class will exist primarily for the purpose of satisfying an interface; if a class exists for the purpose of implementing interface IWuzzler and the most natural description for an instance of the class would be "a Wuzzler", then it may be good to have the public face of the class match the interface as well as possible; the fact that a member would be useful in the class would suggest that it might be useful as a [possibly optional] part of the interface.
In other cases, however, a class will exist for its own purposes but will satisfy an interface so that it can be operated upon by code that isn't apt to care about most of the things the class does. For example, many collection types might implement IEnumerable<T> even though their primary purpose centers around things that most consumers of IEnumerable<T> would know nothing about. If the class implements an interface for the purpose of making instances usable by outside general-purpose code, then the type should be expected to have many members which are not present in those interfaces.
Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.
I'm trying to create an interface to a common class, but the implementation classes can have different parameters.
e.g.
public interface IViewModel
{
//...
void ResetReferences();
}
// and then, in my class implementations, something like this:
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) //...
}
public class ProductViewModel : IViewModel
{
public void ResetReferences(List<Color> colors, List<Size> sizes) //...
}
So notice that I want to standardize on the ResetReferences naming convention. I'm pretty sure I can't do this, but is there a design pattern that could work? e.g. in my interface, something like below?
// variable parameters
void ResetReferences(params object[] list);
But then how do I make I do type checking or having it call the actual method signature that I want, etc?
Maybe an interface is the wrong thing to use? Maybe just a base class and some coding conventions?
Thanks,
Replace your args lists with objects that implement a related interface:
public interface IViewModel
{
//...
void ResetReferences(IResetValues vals);
}
I should add that, IMO, ResetReferences() should not take an argument... it should reset to some default value that would be specific to the individual type(s) that implement your interface..."Reset" being the word that means, to me, "restore to initial state"...adding args implies that you can control that.
The purpose of an interface is to have client code know about the interface and be oblivious of the implementation. If your implementations require special treatment when called, the client code need to know what implementation it is calling and then the whole purpose of the interface is lost.
Unless I misunderstand totally what you're trying to accomplish, you're down the wrong road.
If the parameters can be different, then it isn't really a common interface. Put it this way: does the caller need to know the implementation class? If so, you've lost the loose coupling benefits of interfaces.
One option is to encapsulate the parameters into another type, and make the class generic on that type. For example:
public interface IViewModel<T>
{
void ResetReferences(T data);
}
Then you'd encapsulate the List<Color> colors, List<Size> sizes into one type, and possibly put List<StateProvinces> stateProvinces in another.
It's somewhat awkward though...
You will need to implement the interface method, but you can still do what you want
public class LocationViewModel : IViewModel
{
public void ResetReferences(List<StateProvinces> stateProvinces) // ...
void IViewModel.ResetReferences() // ...
}
You would have to have both methods in the interface (and have the one not correct for an instance throw a non-supported exception), or have the interface inherit from two other interfaces to the same effect.
An interface definition is the entire signature.
It may also be possible to pass an object as a parameter (perhaps derived from a ParameterProvider base class) so that the object encapsulates the dynamic nature and still allows the interface to be static. But that that point you're basically working around the type system anyway.
first question here, so hopefully you'll all go gently on me!
I've been reading an awful lot over the past few days about polymorphism, and trying to apply it to what I do in c#, and it seems there are a few different ways to implement it. I hope I've gotten a handle on this, but I'd be delighted even if I haven't for clarification.
From what I can see, I've got 3 options:
I can just inherit from a base
class and use the keyword
'virtual' on any methods that I
want my derived classes to
override.
I could implement an abstract class with virtual methods
and do it that way,
I could use an interface?
From what I can see, if I don't require any implementation logic in the base, then an interface gives me the most flexibility (as I'm then not limiting myself with regards multiple inheritance etc.), but if I require the base to be able to do something on top of whatever the derived classes are doing, then going with either 1 or 2 would be the better solution?
Thanks for any input on this guys - I have read so much this weekend, both on this site and elsewhere, and I think I understand the approaches now, yet I just want to clarify in a language specific way if I'm on the right track. Hopefully also I've tagged this correctly.
Cheers,
Terry
An interface offers the most abstraction; you aren't tied to any specific implementation (useful if the implementation must, for other reasons, have a different base class).
For true polymorphism, virtual is a must; polymorphism is most commonly associated with type subclassing...
You can of course mix the two:
public interface IFoo {
void Bar();
}
class Foo : IFoo {
public virtual void Bar() {...}
}
class Foo2 : Foo {
public override ...
}
abstract is a separate matter; the choice of abstract is really: can it be sensibly defined by the base-class? If there is there no default implementation, it must be abstract.
A common base-class can be useful when there is a lot of implementation details that are common, and it would be pointless to duplicate purely by interface; but interestingly - if the implementation will never vary per implementation, extension methods provide a useful way of exposing this on an interface (so that each implementation doesn't have to do it):
public interface IFoo {
void Bar();
}
public static class FooExtensions {
// just a silly example...
public static bool TryBar(this IFoo foo) {
try {
foo.Bar();
return true;
} catch {
return false;
}
}
}
All three of the above are valid, and useful in their own right.
There is no technique which is "best". Only programming practice and experience will help you to choose the right technique at the right time.
So, pick a method that seems appropriate now, and implement away.
Watch what works, what fails, learn your lessons, and try again.
Interfaces are usually favored, for several reasons :
Polymorphisme is about contracts, inheritance is about reuse
Inheritance chains are difficult to get right (especially with single inheritance, see for instance the design bugs in the Windows Forms controls where features like scrollability, rich text, etc. are hardcoded in the inheritance chain
Inheritance causes maintenance problems
That said, if you want to leverage common functionnality, you can use interfaces for polymorphism (have your methods accept interfaces) but use abstract base classes to share some behavior.
public interface IFoo
{
void Bar();
enter code here
}
will be your interface
public abstract class BaseFoo : IFoo
{
void Bar
{
// Default implementation
}
}
will be your default implementation
public class SomeFoo : BaseFoo
{
}
is a class where you reuse your implementation.
Still, you'll be using interfaces to have polymorphism:
public class Bar
{
int DoSometingWithFoo(IFoo foo)
{
foo.Bar();
}
}
notice that we're using the interface in the method.
The first thing you should ask is "why do I need to use polymorphism?", because polymorphism is not and end by itself, but a mean to reach an end. Once you have your problem well defined, it should be more clear which approach to use.
Anyway, those three aproaches you commented are not exclusive, you still can mix them if you need to reuse logic between just some classes but not others, or need some distinct interfaces...
use abstract classes to enforce a class structure
use interfaces for describing behaviors
It really depends on how you want to structure your code and what you want to do with it.
Having a base class of type Interface is good from the point of view of testing as you can use mock objects to replace it.
Abstract classes are really if you wish to implement code in some functions and not others, as if an abstract class has nothing other than abstract functions it is effectively an Interface.
Remember that an abstract class cannot be instantiated and so for working code you must have a class derived from it.
In practice all are valid.
I tend to use an abstract class if I have a lot of classes which derive from it but on a shallow level (say only 1 class down).
If I am expecting a deep level of inheritence then I use a class with virtual functions.
Eitherway it's best to keep classes simple, along with their inheritence as the more complex they become the more likelyhood of introducing bugs.
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...*/
}