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.
Related
How to define a must inherit class? in C#
You mark the class as abstract (this is the C# analogue to the VB.NET Must Inherit).
This will ensure it can't be instantiated directly.
From the linked MSDN article:
The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
(emphasis mine)
Use the abstract modifier.
public abstract class MyClass()
{
...
}
You can define a class as abstract, or give it a protected-only constructor. abstract is better.
If u want to create a class, that has to be inherited, you'll need to mark it with the abstract modifier.
public abstract MyClass
{
}
It's not possible enforse needness of derivation or implementation in code, if that was a question.
But:
You can define an interface to force consumer to implement it.
Or you can define abstract class with only abstract members to force consumer to override all of them.
Hope this helps.
An interface would be best.
If you need to simulate the functionality , and its not a requirement that it fail at compile time...
define a method in the base class. Throw a an exception as the only line in the implementation. You might want to make the message very very clear about what the problem is.
override the method in the super class(es) and implement them.
If you fail to implement in a super class, you will get the exception.
Not perfect, but say you are trying to port code from vb.net... this could work.
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...
I have some doubts when to use abstract class and if I need to always code interface. An example:
I have will have series of custom entities, and all of them need to implement SomeMethod() and most of them need to implement AnotherMethod() method.
SomeMethod() will be entity specific, each entity will have different code.
AnotherMethod() is implemented by most, but not all, and the code is the same for all.
How is this modeled? My idea is that each new entity must implement SomeMethod() and is able to use AnotherMethod().
Thanks,
Goran
AnotherMethod should likely be implemented in an abstract class so you don't repeat the code all over the place.
If SomeMethod is related functionaloty, it could be left in the same abstract class without an implementation, forcing children to implement it. If the functionality is not related to AnotherMethod, you could put it in its own interface.
You're right, for SomeMethod(), using abstract parent class with abstract method is a good idea. You can also use interfaces, depending on the meaning of the method. For example, if different classes represent different animals and the method is Move(Coordinate destination), an abstract parent class is better. If, on the other hand, different classes have nothing in common and the method is SerializeToJSON(), you should better use interfaces.
If AnotherMethod() is implemented by some of the classes, again, you can use an abstract parent class (with a non-abstract protected/public method). Of course, don't inherit from this parent the classes which do not have to implement AnotherMethod().
A big difference between interfaces and abstract classes is that the abstract class can have some implementation where the interface is strictly a contract and data type. In the examples you give, you could use an interface to require the implementation of both SomeMethod and AnotherMethod but you wouldn't be able to write any code for AnotherMethod since the interface would just have a method signature.
In an abstract class you could define SomeMethod as abstract and therefore require an implementation from classes which inherit from it but you could also create the implementation of AnotherMethod and have a single implmentation since you say that it will be the same for a lot of your classes.
A good situation to think of replacing inheritance with aggregation.
I'd extract AnotherMethod() to other class, say, AnotherMethodRunner, and add a getAnotherMethodRunner() to a base interface. If AnotherMethod() is a property of derived class, it will have one, if not - it will return null or Null Object.
I personally usually take a nonempty abstract base class as a call to more precise interface extraction.
I've stumbled upon this "feature" of C# - the base class that implements interface methods does not have to derive from it.
Example:
public interface IContract
{
void Func();
}
// Note that Base does **not** derive from IContract
public abstract class Base
{
public void Func()
{
Console.WriteLine("Base.Func");
}
}
// Note that Derived does *not* provide implementation for IContract
public class Derived : Base, IContract
{
}
What happens is that Derived magically picks-up a public method, Base.Func, and decides that it will implement IContract.Func.
What is the reason behind this magic?
IMHO: this "quasi-implementation" feature is very-unintuitive and make code-inspection much harder. What do you think?
The reason is that your comment is simply incorrect:
// Note that Derived does not provide implementation for IContract
Sure it does. Follow the logic through.
Derived is required to provide a public member corresponding to each member of IContract.
All inheritable members of a base class are also members of a derived class; that's the definition of inheritance.
Therefore Derived provides an implementation for IContract; its inherited member is a member that fulfills the requirement
Therefore, no error.
this feature is very-unintuitive and make code-inspection much harder. What do you think?
I think you shouldn't use the feature if you don't like it. If you find it confusing and weird to read code that uses this feature then encourage your coworkers who use this feature to stop doing so.
How is this feature different from any other feature where a method from a base class is used from a derived class? There are a number of different ways in which a method from a base class may be used or mentioned in a derived class -- method calls, overrides, method group conversions, and so on.
Furthermore, this is relatively speaking a simple, straightforward case. If you really want to complain about confusing interface semantics in C#, I'd spend my time complaining about interface reimplementation semantics. That's the one that really seems to bake people's noodles. I always have to look that thing up in the spec to make sure I'm getting the semantics right.
Why do you think that this is strange and unnatural? Every public member of base class is also a public member of derived class. So there is no contradiction here. Anyhow you can implement interface explicitely if you like.
In base class constructors I always see a parameterless constructor, like so:
public abstract BaseClass {...
protected BaseClass() { }
...}
but is it acceptable design to include a parameter in the base class constructor?
public abstract BaseClass {...
protected BaseClass(string initObj) { }
...}
Yes, it is acceptable for a base class to require a parameterized constructor. This simply imposes a requirement that any classes which inherit must provide a value to the base constructor.
In most cases the derived classes have some form of parameterized constructors.
So when those constructors are called they can still call the parameterless base constructor:
public employee(int age) : base(this)
The answer is if you need one just add one, there is nothing wrong with that. Think of a business object base class that requires some validations to say a phone number or email address. You want to ensure the derived classes get these business rules loaded into them. If you did not have the base class constructor you could not add these rules to your derived class objects.
It is a good practice if the object cannot be used or has dependencies on every method on this class. For instance, if you have a class that have the same parameters in all the functions, it would be better to set that in the constructor, so the function signature is smaller.
What the writer of the base class is doing in your first example is just making sure that no public constructors are exposed. Probably the base class needs nothing special in the constructor but, if you don't write any, the compiler will add the default (parameter-less) constructor for you.
Not that I think this is specially useful. You cannot instantiate an abstract class anyway.
It is certaibly acceptable. Whether is is needed or useful depends entirely on the (design of) the classes.
Yes, its a perfectly acceptable design decision, only it must make sense for the base class - presumably to initialise its own members from the parameter. Also, it imposes a restriction on derived classes: either they must pass in a literal, or impose a similar restriction on their clients or further derived classes.