Make a method available to deriving class, but not beyond that - c#

Is there a way to make a method in a base class (Custom, so editable) public to classes that inherit it, but not beyond that?
I want the given method to be "private" within all classes that 'contain' it, but to not be accessible from other classes.
A little context:
I have three very similar classes, and am creating a base class with some properties and methods that the three classes share. Some of these properties and methods are private and should be, but I can't set them as private in the base class or they can't be accessed within the three.

You are looking for the protected access modifier.

You want the protected keyword:
http://msdn.microsoft.com/en-us/library/bcd5672a(VS.71).aspx

The protected access modifier probably is what you're looking for. A protected member is accessible within its class and by derived class instances.

Related

create mustoveride function with code in it

I have a MustInherit class with some MustOveride Methods in it. When i inherit form that class, I automatically get the MustOveride Methods or properties.
My question is, I want to be able, to inherit from a class, get my MustOveride functions and methods, but then with some code already in it. I've once seen a .net class that did it, when I inherited from that class, I got the methods, with some comments in it.
Does anybody have an idea what i mean? (It a bit hard to describe ;-) )
I think what you described is known as Template Method Pattern:
public abstract class MyClass
{
public void SomeMethod()
{
// code
MustInherit();
// code
}
protected abstract void MustInherit();
}
Create a method which will not be overridden SomeMethod in this sample and stuff all common code into this class. Then create an abstract method which must be overridden.
If you want to provide a default implementation, so the method must not be overridden but can be use the virtual keyword.
public abstract class MyClass
{
public void SomeMethod()
{
// code
MustInherit();
// code
}
protected virtual void CanInherit()
{
// default implementation
}
}
I assume, you want to do have the following:
When you inherit from that abstract base class, you want to have those abstract methods already partly implemented in your class.
This is not possible out of the box. It could be achieved with some templating, but that has nothing to do with C# or VB.NET but with the IDE used.
The only thing you can do is to create that method as virtual (C# - I don't know how it is called in VB.NET) in the base class and call the base implementation in the derived class.
An Abstract class for you service :)
If you need that consumer of your abstract class ovverides some methods for sure then mark them as abstract too. If you need just to provide possibility of ovveriding you methods but this is not definitely necessary then mark them as virtual.
With the virtual keyword you are not forced to implement the inherited method, then it will use the default implementation of the base class. In that way, you kind of inherit all the code from the base method.
Otherwise, you can implement you own derived version of the method, and somewhere in it call the base class' version of method : base.MethodName(...);. That allow you to kind of inherit all the code from the base method once again, but this time with additional code before and after which is specific to your derived class.
Otherwise, you can make your base class' method such that it uses delegates in its code and call it here and there. Thus the fundamental functioning of the base class' method remain the same for all the derived classes, but each derived class provides its own delegates to adjust some detail key blocks of code in the base class' method.
Otherwise, if you want to see partially implemented methods with comments here and there like Add your code here, it's typically a matter of code generated by an external tool like Visual Studio or another IDE and has nothing to do with the language itself.
But as you see there are plenty of possibilities, depending of you you want precisely...

Is there a way to have a public method, which won't be inherited?

I have a class, with public API.
I have other classes who inherit from that class.
I do not make use of all the APIs inherited from the first class.
If I change the order of inheritance, then I have even more API methods I do not wish classes to inherit.
Languages: PHP and C#
If some method should not be in inherited class, you probably should not place its in base class.
Second class could implement some interface which has that method, or inherit by another class which has that method and is inherited by current base-class.
Is there any specific reason why you would want such method? I think you should consider putting the functionality you want your classes to inherit in an interface. Other functionality should be implemented as private methods.
Also consider breaking down the functionality into several classes and then using Composition instead of inheritance. If you use inheritance to compose complex class hierarchies, they will always be difficult to manage. You should favor composition over inheritance.
I would suggest you to use Decorator pattern.
If we call the base class B and the derived classes D1, D2...
Two approaches are:
Split B into two classes: the private implementation (abstract B) and the public methods (that you wish to hide in your other 2 classes), D3. So to "use" the base class you instantiate D3. Then D1,D2 only inherit the private implementation of B because the public interface for "B" is only available through D3. (If you still need some of the public functionality in D1,D2 but don't want it to be public, then simply add it as a private method od B, and then add a public proxy method in D3 that exposes it and simply calls down to the base class implementation.
Don't derive your classes from B. Embed an instance of B in D1,D2 and simply expose a new interface in those classes that only makes the "limited functionality" available.
I do not make use of all the APIs inherited from the first class
put those methods to a public sealed class
I have other classes who inherit from that class.
use Interface of base class with virtual methods for that.

Protected Keyword C#

I want to know what is the meaning of protected in C#, why we use it, and the benefit of the keyword?
For instance
protected int currentColorIndex;
Please elaborate.
Everyone's answer is similar (a definition and/or a excerpt/link to MSDN), so ill attempt to answer your original 3 questions:
The Meaning:
Any field marked with 'protected' means it is only visible to itself and any children (classes that inherit from it). You will notice in the ASP.NET Web Forms code behind model, event handlers (such as Page_Load) are marked 'protected'. This is because the ASPX Markup file actually inherits from the code-behind file (look at the #Page directive to prove this).
Why We Use It:
The common use of the protected accessibility modifier is to give children access to it's parents properties. You might have a base class for which many subclasses derive from. This base class may have a common property. This is a good case for a protected property - to facilitate the re-use and central maintenance of common logic.
The Benefit:
Kind of similar question to "why we use it?" But essentially it gives coarse-grained control over properties. You can't just think of "when you use protected". It's more a case of choosing when to use which accessibility modifier (private, public, internal, protected). So the benefit is really the same benefit of any accessibility modifier - provide a robust and consistent object model, maximising code re-use and minimizing security risks associated with incorrectly exposed code.
Hope that helps.
As others have already pointed out:
The protected keyword is a member
access modifier. A protected member is
accessible within its class and by
derived class instances.
Here is a small example:
public class A
{
protected string SomeString;
public string SomeOtherString;
}
public class B : A
{
public string Wrapped
{
get { return this.SomeString; }
}
}
...
var a = new A();
var s = a.SomeOtherString; // valid
var s2 = a.SomeString; // Error
var b = new B();
var s3 = b.Wrapped; // valid
"A protected member is accessible from
within the class in which it is
declared, and from within any class
derived from the class that declared
this member."
see
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected
Straight from the MSDN:
The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances.
Source
Using protected means you can have functionality in a class that's available to derived classes, but not to classes that just instantiate the object.
This page compares the different access modifiers and explains what they mean and gives a table of the default modifiers for different objects (enum, class, interface and struct).
Definition provided in another answer. Why is this good? You don't have to duplicate data/code from base class to its derived classes when protected offers them access to base class implementations, without the unwanted exposure to unrestricted external usage that would be implied by public.
It means that the field is only visible to the class itself and inherited classes.
Think of it like this. A class presents three interfaces:
Towards itself, with full access to internal implementation details (public, protected, private methods and attributes). By definition, anything you do in a class may affect anything else.
Towards its clients, with access only to the public methods and attributes. You minimize the public interface of a class in order to minimize unexpected consequences of changes: the less code knows about your internals, the more freely you can modify them later.
Towards its descendants, with access to the public and the protected methods and attributes. Whatever you do to protected and public methods will impact not only clients, but also descendants that modify the base functionality of your class. OO is about reducing coupling and increasing cohesion: there is no stronger coupling between classes than the inheritance relation (well, apart from the C++ friend, of course)!
The third interface is the hardest general design challenge in OO: what can reasonably be overridden (virtual methods and properties), and in order to override, what other functionality is needed (plain protected methods and attributes)? Because this is such a challenge, having classes sealed by default is actually a good idea, counterintuitive as it frequently seems to OO beginners, to whom it seems like an unnecessary handicap.

Interface and base class mix, the right way to implement this

I have some user controls which I want to specify properties and methods for.
They inherit from a base class, because they all have properties such as "Foo" and "Bar", and the reason I used a base class is so that I dont have to manually implement all of these properties in each derived class.
However, I want to have a method that is only in the derived classes, not in the base class, as the base class doesn't know how to "do" the method, so I am thinking of using an interface for this. If i put it in the base class, I have to define some body to return a value (which would be invalid), and always make sure that the overriding method is not calling the base. method
Is the right way to go about this to use both the base class and an interface to expose the method? It seems very round-about, but every way i think about doing it seems wrong...
Let me know if the question is not clear, it's probably a dumb question but I want to do this right.
EDIT : Thanks to all the people with your excellent abstract suggestions, but this breaks the designer. If abstract was not a selectable option, what would you do?
Alternatively you could define the method as 'abstract' in the base class, which will not require the class to implement it. For example:
abstract class A
{
public abstract void B();
}
Of course this will force your base class to be abstract as well, but it sounds like this would work just fine for you.
See Abstract methods on MSDN.
Update
Since abstract is not an option for you due to designer issues, you could just define the method as part of your base class, and have it throw a NotImplementedException if it is called directly from the base class:
void DerivMethod()
{
// Must be implemented by derived class
throw new NotImplementedException();
}
Otherwise, using an interface would be fine, especially if the above leaves a bad taste in your mouth...
You should make your base class an Abstract class. Then the base class can implement the Interface by marking the method abstract.
http://msdn.microsoft.com/en-us/library/aa664435(VS.71).aspx
Mark the method as abstract in your base class. You'll be forced to implement it in the derived classes, but the base class will not need to have a method definition.
I agree with with others, but making your user control abstract has some issues for the designer. The designer will often not display the abstract user control.
I would implement the interface methods in the base class. You can throw a NotImplemented exception or Assert.Fail in the methods if you want to make sure the inheritors are overriding these methods properly.
Declare the function signature in the base class and use the "abstract" modifier.

Implementing an Interface but changing a member to be private

All members of an Interface are public by default. But there are some properties in my interface that I want to be used as private members of some subclasses that implement my interface. Is this something that can and is done or am I way off basis here. I'm working on using more Interfaces in my architecture these days so I'm not that well versed yet.
The point of interfaces is that they provide a contract that other objects can use to communicate with your object. If you change a member which is declared as public in an interface to private then you're not fulfilling the contract - another object may need to read that property / call that method, and you must allow them to.
An interface will never have private members as an interface is for "interfacing" between two objects. Your internal private members don't matter to it as long as you hold up your end of the contract.
Going on your question, and your use of the word "subclass", I don't think you've fully understood Interfaces yet.
I know you've probably heard this a million times but, an Interface describes what an object DOES, and a Class is HOW it does it. A Class IMPLEMENTS, an interface, it does not INHERIT from it.
So, if you want, have an Interface for you base Class, or for your SubClasses, but your question makes me think you're thinking about a base Class (Abstract Class), not an Interface.
Does that make sense?
As interface does not has an Access Modifier, if you still want your method private in the class which is implementing that interface, you can Implement that interface EXPLICITLY.
In that way your class methods will be Private.
You have to fully understand what interfaces are. In fact there are just descriptions of the expectations that outside world could have about the class members. It do not creates the member, it just informs that specified class have specified method to use in public scope. So, as you can see by interface you could only describe public members.
On the other hand if you want to declare some private members that are fixed or virtual you can use classic inheritance with the abstract base class. In this case you will make all methods that you want to implement in subclasses as abstract, and implement methods that you want to be defined in base class.
Hope this helps.. Regards
Interfaces are only good for public access. Internally, it would be strange for an object to refer to itself through an interface.
If you want to have private variables that you force an implementation of, you want to use an abstract class, and mark them as protected.
Think a little about this - and you understand that this can not be done:
Interfaces are like a contact. all the public fields of the interface are parts of the contact.
So, you can't hide them in a subclass... What would happen if someone were to upcast your class object to the interface's type ?
You'd probably want to change your design - may be split your interface in to two interfaces?
or and interface and an abstract class? we need more details to know...

Categories

Resources