Is there a way to not be forced to include members with the MustOverride property when you inherit? I'm working on a custom MembershipProvider, and I only need access to a few members. It's purely an aesthetic thing - I just hate having to stub out 100 lines of unused member declarations.
You can right click the inherited class and select "Implement this ..." and it will create the method definitions for you throwing NotImplementedException() until you rewrite the method's code.
MustOverride (abstract in C#) specifies that it must be overridden. There is no way around this.
You can have Visual Studio stub out the features for you, but they need to exist in order for the class to be instantiated.
One other option: If you'll be doing multiple versions, you can make a class that implements the members (throwing NotImplementedException, or doing nothing), and then derive from THAT class. Your concrete version only would need to have the specific methods overriden that you wish.
No, there is not.
Btw, MustOverride is usually called abstract in C#.
Yes there is... Declare your class as abstract, too! :-P
Now, seriously, just think about it. If you would not implement an abstract member in a non-abstract class, imagine what would happen at runtime, when calling a method without implementation? In C++, this was possible, and you would get a "Pure virtual function call" error.
Related
I have a problem with inheriting a custom generic. The compiler (Visual Studio for Mac), complaints that the inheriting generic can't be implicitly converted to another, inheriting type. A break down of my code is as follows:
I have an interface called IAnsweredCommon and another interface that inherits from it called IAnsweredAndroid
public interface IAnsweredCommon
and
public interface IAnsweredAndroid : IAnsweredCommon
I have two other classes that use these interfaces.
public abstract class ConstructorCommon<AnsweredType> where AnsweredType : IAnsweredCommon
and
public class ConstructorAndroid : ConstructorCommon<IAnsweredAndroid>
This works. The common constructor has a member variable of AnsweredType allowing it to treat it as IAnsweredCommon and run OS agnostic code against it, while allowing the Android constructor access to the same member variable and can treat it as IAnsweredAndroid allowing the Android constructor to run Android specific code against it. The Android constructor can handle Android specific things while passing OS agnostic code to the common constructor. This works and is what I want as it allows me to extend this to iOS.
Now the problem is that I have another layer on top of the constructor. The constructor basically implements the builder design pattern and so it has lots of methods to call in order to construct an answered object. I have director classes that call predetermined constructor methods to create a predetermined answered object.
public abstract class DirectorCommon<AnsweredConstructorType>
where AnsweredConstructorType : ConstructorCommon<IAnsweredCommon>
and
public class DirectorAndroid : DirectorCommon<ConstructorAndroid>
The compiler complains about being unable to implicitly convert ConstructorAndroid to ConstructorCommon<\IAnsweredCommon>. I've expanded upon ConstructorAndroid for testing purposes and I've temporary changed it to be:
public class DirectorAndroid : DirectorCommon<ConstructorCommon<IAnsweredAndroid>>
Now, if I change the IAnsweredAndroid interface to IAnsweredCommon, the error goes away (as it should since it exactly matches the constraint). But if I change it to IAnsweredAndroid, I get the error. I'm confused as IAnsweredAndroid IS IAnsweredCommon (inheritance) and therefore, the compiler should be able to upcast IAnsweredAndroid to IAnsweredCommon. After all it's doing this in the constructor classes.
NOTE: I've cleaned up the code to make it easier to read (removed namespaces, irrelevant code and what-not) so the code maybe not be 'runnable', but regardless, please point out any errors and I'm sure it's a minor thing I'm missing and you never know if an error is because of the clean up or if it's an actual error.
That is not possible, class<A> is not assignable to class<B>, also if A derives from B or vice versa.
It would work, if ConstructorCommon would be an interface, IConstructorCommon, and be defined as:
interface IConstructorCommon<out AnsweredType> where AnsweredType : IAnsweredCommon
The "out" makes it covariant.
To replace an abstract base-type with an interface, might be suitable.`
Your error has nothing to do with the constraint, the way you found just matches, cause the type matches. You can assign a ConstructorComman<Android> to ConstructorCommon<Android> but not to ConstructorCommon<Answer> no matter if there is a constraint or not. Constraints you need only if you want to call special methods, that only your constrained-type has.
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.
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());
}
I feel like this should be very possible.
I have an interface, let's call it IJerry. Now, I have a class in variable x. That class implements IJerry perfectly. The thing is, that class does not ever reference IJerry. It just happens to have a perfect, compliant signature with IJerry.
Make sense? Let's say you create a class called MyClass that implements INotifyPropertyChanged. Then you delete the MyClass : INotifyPropertyChanged declaration from the class but you LEAVE the implementation inside the class.
Is there a way to determine if the class "implements" an interface even if it does not make an explicit reference to it?
Not easily.
You would have to read the fields, method, and properties of the interface using reflection, and then check if the class has them (again using reflection)
Alternately, if you are using C#4, you could just forget about IJerry, and put MyClass in a dynamic variable, and then you C# figure out at run-time for it has the methods being called.
There's a lot more to implementing an interface than meets the eye. For one, implementation methods are virtual, even though you don't use that keyword. In fact, you're not allowed to use that keyword. For another, the compiler rearranges the methods to match the method table layout of the interface. Removing the inherited interface from the declaration is guaranteed to make the result incompatible. The methods won't be virtual anymore.
What you are pursuing is called 'dynamic dispatch'. Implemented in the DLR and integrated into .NET 4.0 and the C# 4.0 language. Re-inventing the System.Reflection code and making it efficient is a major undertaking.
You would have to use reflection to see if x had methods that matched the ones on IJerry. The real question is, what are you going to do with the answer? Prior to version 4, C# doesn't support "duck typing", so in order to use your class where an IJerry is required you have to write adapter code.
I usually make a base class abstract to give the signal this is a base class - you cannot instantiate me! even if there are no abstract methods in it.
Furthermore, I always make the base class constructor protected, although there's no real functional need to do that - I just want to make another point that this is a base class - you cannot instantiate me!
Am I jumping through hoops in doing that? What do you do?
It seems a reasonable thing to do, yes. There'll be no functional difference between the constructor being public or being protected, but making it protected gives a clearer indication of the intended use.
I'm not sure that you should set the class as abstract if there are no abstract methods. If it has a full implementation of the functionality that is expected of the classes derived from it, why not let it be instantiated and used as is? If this is just a way to share functionality across a range of classes then a composition based design may be more appropriate ie. have each 'derived' class reference this class rather than derive from it.
Is there a particular scenario you have in mind where this is could be an appropriate design?
Edit
The only scenario I have found where an abstract class with no abstract methods makes sense is when the abstract class is partially implementing and interface. The derived classes are required to complete the implementation.
Link to example (edit: site gone, This blog post seems to be a copy of the content)
In an abstract class, there's no difference between a public or protected constructor. As a matter of fact, I believe the compiler should give a warning or error when defining the constructor of an abstract class as public. Too bad it doesn't.