abstract method override in Derived class, how to make private - c#

Hi I have a class "A" with as abstract method
protected abstract List<Contributor> GetContributors(List<SyndicationPerson> contributersList);
I want to override this method in derived class "B" with following conditions
It should be private to B class.
compiler does not allow me to declare this Method as private in derived class "B"
what is the correct syntax ?

You can't. That would violate the accessibility level declared in class A. Aside from anything else, it would stop it from being callable by class A! What would you expect to happen if code in class A tries to call the abstract method which you'd somehow overridden with a private implementation?
You can make the main implementation private and then create a protected method which just calls the private one, if you really want to.
Why do you want to make the method private in the first place, when it's designed to be callable from A?
EDIT: Okay, now you've explained in your comment what you want to do, you can't do it. The closest you can come is to pass a delegate to A's constructor - that delegate can refer to a private method. Unfortunately, you can't use "this" when you pass arguments in constructor chains, so you're forced to do something horrible such as writing a static method which takes "this" as its first parameter, effectively... except that it will have to cast it to the right type as well, as the parent can't declare which type it should be. The parent would then call the delegate instead of the protected method.
Note that this would also prevent further derived classes from "overriding" further, which may or may not be desirable.
It's incredibly tortuous, and I'd try to avoid it wherever possible. If you're really worried about what derived classes might do, I'd try to seal the class instead and force people to use composition instead of inheritance. The language doesn't really help you do what you want to here.

As a general OOPS rule, one cannot reduce the visibility of a member when overriding. So going from protected to private is not allowed.

You cannot change access level of virtual methods in C#. You can redeclare it by using the new keyword, but this is a redeclaration that hides the previous method, so it will not work as you expect if you're dealing with objects that differ in declared and actual type, or if you routinely cast objects to a base class type.

Related

Correct way to see if the current instance of a superclass is a subclass from within the superclass

Say I have a class called SuperClass and a class called SubClass. SubClass extends from SuperClass. Inside the definition of SuperClass I have a method that intends to check if this class is an instance of SubClass.
if (this.GetType() == typeof(SubClass))
log.Info("This SuperClass is a SubClass");
else
log.Info("This SuperClass is NOT a SubClass");
This works, but I'm always very skeptical when something works correctly (especially on the first try). I wanted to make sure this was the best way (safest, most readable, correct) to do what I want.
I think you're just looking for the is operator:
if (this is SubClass)
In particular, that will also continue if this is an instance of a subclass of SubClass.
If you then want to use this as SubClass, e.g. to get at a member declared in SubClass, you should consider the as operator too:
SubClass sub = this as SubClass;
if (sub != null)
{
// Use sub here
}
If you want to detect that this is an instance of exactly SubClass (and not further derived types) then the check you've got is already the right one.
One word of warning: the need to check for types at execution time is often a bit of a design smell. Think about whether there are alternative ways of achieving whatever your goal is. Sometimes there are (e.g. by introducing a new virtual or abstract member in the base class) and sometimes there aren't... but it's always worth thinking about.
This will work but you've coupled your super and sub classes where the super really shouldn't know about the sub. Create a virtual method on the super class that the sub will override to do the actual work. You can call this method from inside or outside of the super class to do the work you need. If the work needs to be done on members of the super class, then make them protected so the sub class can access them.
Let me add that almost anytime you need to check the type of an object, you aren't doing object oriented programming correctly and there is a better design to be found. Usually it's the sub class that needs to be doing the work that the type checking class is trying to do.

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...

Hide Virtual function In Inherited Class

I have a class that inherits from LinkButton and I want to hide OnClinentClick from my class.
Somthing like this :
public class MyClass : LinkButton
{
// some Code
}
And somewhere in code:
MyClass myclass = new MyClass();
MyClass.OnClinentClick = "";//this line must not be accessable
Hiding something from a class definition is not directly supported as it breaks OOP principles.
You could use the new operator, however, I wouldn't advise it. Personally, I would think about my design and/or use a NotSupportedException if there is no other way around it.
You can use the EditorBrowsableAttribute to prevent it from being suggested by IntelliSense, but you can't get rid of it entirely.
[EditorBrowsable(EditorBrowsableState.Never)]
public virtual string OnClientClick { get; set; }
C# only supports public inheritance. You shouldn't be inheriting from a class whose methods don't make sense for all derived classes. Consider composition instead of inheritance to solve this problem.
You can override the function (that is, replace the base implementation with your one, as long as the former is virtual), but you cannot completely prevent the clients from calling the base class function if you hide it with new, as they may always cast to the base class.
Update:
actually, you cannot change the access from public to protected/private when overriding, this won't compile (http://ideone.com/Y65Uh). Besides that, if you use new to hide the base function and make it uncallable, the original function is still visible (http://ideone.com/xiL2F). If you declare the new function public (which is perhaps not what you want), the old function can still be called by casting to the base class (http://ideone.com/A3Bji).
How about making giving it a lower visibility. One of protected and internal might be what you want. Of course that doesn't remove such a member from the derived class, but just removes them from the public interface. It also requires control over the base-class. No idea if LinkButton is one of your classes.
You could also hide the property by reintroducing a new one with the same. But that's a bad idea, and casting back to the base-class allows outsiders to access it.
And you should consider using a has-a relationship instead of an is-a. i.e. Don't derive from a base class if you don't want all its public members. This violates OOP principles such as that it should be possible to substitute the derived class where the base class is expected.
You could also override it, and make the setter throw a NotSupportedException. But that's ugly too because it will only show an error at runtime instead of compiletime. You can generate compile-time warnings with attributes such as the ObsoleteAttribute.

When overriding a method should my custom code come before or after super(base)

When overriding a method should my custom code come before or after the super(base) call to the parent class?
There are 3 choices you have here:
If you want to execute the base behavior before your code, then call it before.
If you want to execute the base behavior after your code, then call it after.
If you want to completely override the base behavior, don't call it at all.
It is important to also check your API's documentation. Some classes have subclass contracts that are not enforcable by code, but that can break behavior if you don't follow their rules. There are some cases where subclasses are required to call the super implementation.
This will depend on when you want your code to execute: before or after the base method.
It depends on You want to make something before or after orginal method. Good practise is to write custom code after super call. That becase you ADD some new code.
It depends of the behavior you want. You don't even have to call super's method at all. The place you call it will depend if you want your code executed before or after the base class code.
Like most things, the simple answer is: it depends.
Specifying super or base allows you to "extend" the method, by adding functionality to what already exists in the base implementation. That code may need to be performed before, after, or on both sides of the call to the base functionality. It all comes down to what your overridden implementation needs to do above and beyond the base implementation.
There are some places, at least in C#, where you cannot choose. For instance, constructors of derived classes in C# have to define a base constructor in their declaration (the default is the parameterless constructor if one exists). The code of the base class is ALWAYS executed BEFORE the derived class, and you can't simply call base(x,y) from within the constructor.
The dependencies of your subclass instance variables with respect to your superclass parameters will determine where your code goes (Java):
private final Baz baz;
public SubClass(Foo foo, Bar bar) {
Qux qux = QuxFactory.getQuxForFoo(foo);
super(bar, qux);
/* getSize() is a method defined on our super class */
baz = BazFactory.getBazOfSize(getSize());
}

Force calling the derived class implementation within a generic function in C#?

Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead.
Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use.
For ease of understanding I've created a small example as follows:
class StandardBaseClass {} // These are simulating the SMO objects
class StandardDerivedClass : StandardBaseClass {
public object Parent { get; set; }
}
static class Extensions
{
public static object GetParent(this StandardDerivedClass sdc) {
return sdc.Parent;
}
public static object GetParent(this StandardBaseClass sbc)
{
throw new NotImplementedException("StandardBaseClass does not contain a property Parent");
}
// This is the Generic function I'm trying to write and need the Parent property.
public static void DoSomething<T>(T foo) where T : StandardBaseClass
{
object Parent = ((T)foo).GetParent();
}
}
In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass.
This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation.
I see this behaviour as a bug. Has anyone else out there encountered this?
I see this behaviour as a bug.
This behavior is correct. Since your method DoSomething is constraining T to StandardBaseClass, you only have access to the specific methods of StandardBaseClass, not any methods or properties of a derived class. Since StandardBaseClass does not have a Parent property, this is invalid, and should be invalid, by design.
There are two potential options here - You can use reflection to pull out the Parent property, or use C# 4's dynamic type, and treat this as a dynamic object. Both bypass the standard type checking in the compiler, however, so will require you to do extra type checking at runtime to verify that the Parent property exists.
Create an interface that contains the Parent property. Have each class that has a Parent property implement that interace. You will then be able to create a generic method that accepts a parameter of type IHaveParent, and it will do the right thing.
For anyone that is interested an succinct answer to this situation is answered by Stephen Cleary on msdn here:
http://social.msdn.microsoft.com/Forums/en-AU/csharpgeneral/thread/95833bb3-fbe1-4ec9-8b04-3e05165e20f8?prof=required
To me this is a divergence in the class hierarchy. By this this I mean that either the base class has parent, or the derived classes with Parent are derived from an abstract child of the base.
Lol as John says, an interface as opposed to an abstract class is sufficient too.
You idea won't work because the compiler can never guarantee that the base class actually would have such a property. And it won't just select the "right" one based on if it has it or not.
The only way you can do this is using reflection and then test at runtime if the requested property exists on the inspected class. You have to judge yourself if that is a viable way to do for your project (reflection is slow and requires maximum rights).
This is correct, as the compiler only knows that it can bind to your type as a StandardBaseClass. The binding is not done at runtime (where it could potentially decide to use the StandardDerivedClass overload.
If you know that it's a StandardDerivedClass, then why not just cast it as such?
object Parent = ((StandardDerivedClass)foo).Parent;
It's a bit ugly, but you can accomplish this using a Registration system, where you register delegates for different possible derived classes that expose the 'shared' property/method and then use something like a Dictionary<Type,Func<SomeT>> to store the delegates. If you know all of the derived types ahead of time and don't have to load plug-ins or the like, you can also use the classic ugly if/else-if structure. Either way you're basically creating your own substitute for what should have been supported by the virtual method table.

Categories

Resources