How to require an implementation of an abstract class in C#? - c#

I want to build a class that would have a property, in which there is an instance of a class, which implements an abstract class. Here's and example.
public class MyClass {
public MyDerivedClassA derived;
public void mainClassUtility () {
derived.foo();
}
}
public abstract class MyAbstractBaseClass {
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass {
public override void foo(){
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
return;
}
}
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use. There will be many implementations of the abstract class and depending on the current state of the program, MyClass might be using different implementations of the ABC. I want to write the program in a way, that no matter what implementation of the ABC is currently being used, there is a way to call it's methods by MyClass. What would be the best solution to this problem?

Unless I'm misunderstanding the question, you're pretty much there. Have MyClass expect a property of the abstract base class and you should be all set.
using System;
public class Program
{
public static void Main()
{
var myClassOne = new MyClass(new MyDerivedClassA());
var myClassTwo = new MyClass(new MyDerivedClassB());
myClassOne.mainClassUtility();
myClassTwo.mainClassUtility();
}
public class MyClass
{
public MyAbstractBaseClass Derived;
public MyClass(MyAbstractBaseClass derived)
{
Derived = derived;
}
public void mainClassUtility ()
{
Derived.foo();
}
}
public abstract class MyAbstractBaseClass
{
public abstract void foo();
}
public class MyDerivedClassA : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassA");
return;
}
}
public class MyDerivedClassB : MyAbstractBaseClass
{
public override void foo()
{
Console.WriteLine("I am MyDerivedClassB");
return;
}
}
}

How to require an implementation of an abstract class in C#?
You can not instantiate a abstract class - and thus can not use it for most cases. Except as variable/argument/generic type argument. You need to make a concrete (non-abstract) class that inherits from it. You can only use the abstract class as a variable/argument type. To guarantee that only stuff that inherits from it can be used there.
Basically, I want to make sure the object I'm using is derived from an abstract class and implements all the methods I will need to use.
Then use the abstract class as type argument. It means only instaces of the abstract class (of wich there can be no instance) or instances of classes that inherit from it (that somebody else writes) can be used at that place.
Note that Abstract classes and Interfaces overlap in nearly all uses. There is a miriad small differences, but I do not think they mater. The only big difference I can see, is one of exclusivity:
a class can implement as many Interfaces as it wants.
You can only inherit from one abstract class. that means it is for a primary, exclusive purpose. That way you prevent some dumb ideas, like someone trying to make a Windows Form that is also a DBConnection.

Related

C# abstract class desgin, is that possible put a constuctor in abstract class and call base to access them

I was practicing c# abstract class and inheritance, but I was wondering if derived classes could access the constructor by calling the base
public abstract class A
{
protected bool value_A;
protected int value_B;
public A(int input)
{
A = true;
B = false;
}
public abstract int function_B();
}
}
public class childA : A
{
public childA (int input):base(input)
{
}
public override int function_B()
{
//do smth
}
}
public class childB : A
{
public childB(int input):base(input)
{
}
public override int function_B()
{
//do something different
}
public void functionC(int input)
{
}
}
I was confused if I should use this abstract class design or just go ez by using inheritance -> declare a virtual function in class A.
Yes, you can. Derived class c'tor can call base class one, even if the base class is abstract.
Generally, using abstract base class makes sense if there is a common functionality (or traits) that you want to reuse, and instantiating the base class does not make sense (and therefore you make it an abstract class).
A basic example is "Shapes" hierarchy, with abstract base class Shape that has color and center (for instance) and virtual method Draw, and all specific shapes inheriting from Shape and implementing the actual Draw functionality for each specific shape.

Interface and abstract class in this case

In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface. I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something?
I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface.
I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface.
Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods
public abstract class Base
{
public void TemplateMethod()
{
AbstractMethod1();
AbstractMethod2();
}
public abstract void AbstractMethod1();
public abstract void AbstractMethod2();
}
public class Concrete : Base
{
public override void AbstractMethod1()
{
Console.Write("Override Abstract Method 1");
}
public override void AbstractMethod2()
{
Console.Write("Override Abstract Method 2");
}
}
public class Main
{
public Main()
{
var concrete = new Concrete();
concrete.TemplateMethod();
}
}

C# Deriving a class from more than one abstract class

I created two abstract classes and tried to create a class that inherits from both. But I get an error message.
abstract class AbstractClassOne
{
public abstract void ShowMessage();
public abstract void DisplayName();
}
abstract class AbstractClassTwo
{
public abstract void ShowMessage();
public abstract void DisplayPlace();
}
class DerivedClass : AbstractClassOne, AbstractClassTwo // here under AbstractClassTwo it shows the error "cannot have multiple base classes:"
{
}
So a class can only derive from one abstract class?
If can derive from more than one abstract class, then what happens if both classes define the same method, as is the case above (abstract class one and two both have a method showmessage(), so which one will be in the derived class)?
Multiple inheritance is not allowed by C# but it is allowed by C++.
To answer your question regarding the ShowMessage() method that is a known problem in c++ with multiple inheritance called "The Diamond Problem". see: http://en.wikipedia.org/wiki/Multiple_inheritance
So basically you will have to excitability state to which method you are refereeing when calling it e.g. ParentA::ShowMessage()
if you want to have a type that is polymorphic to 2 other types than you should create two separate interfaces and implement them. and if you want to reuse the same methods than you will have to use compositions.
Interfaces example:
public interface ISomeInterface
{
public void ShowMessage();
public void DisplayName();
}
public class ClassOne : ISomeInterface
{
public void ShowMessage()
{
//implementation
}
public void DisplayName()
{
//implementation
}
}
public class ClassTwo : ISomeInterface
{
public void ShowMessage()
{
//implementation
}
public void DisplayPlace()
{
//implementation
}
}
Interface with reusable Show Message Method using composition:
public class ClassTwo : ISomeInterface
{
private ISomeInterface _MyPrivateReusableComponent = new ClassOne();
public void ShowMessage()
{
_MyPrivateReusableComponent.ShowMessage()
}
public void DisplayPlace()
{
_MyPrivateReusableComponent.DisplayName()
//implementation
}
}
In C# it's not allowed to inherit from more than one class. To do what you want here, you need to use interfaces.
abstract class AbstractClassOne
{
public abstract void ShowMessage();
public abstract void DisplayName();
}
Interface IClassTwo
{
void ShowMessage();
void DisplayPlace();
}
class DerivedClass : AbstractClassOne, IClassTwo
{
}
You can't inherit from more than one class (abstract or otherwise), but in your case the abstract classes are pretty much interfaces, so you can turn them into interfaces and inherit from them (you can inherit from any number of interfaces).
No, abstract class whether having all abstract methods or only some, makes no difference as far as inheritance in concerned. you can inherit only one class (in C#) and as many interfaces as you want.

Sealing an interface after implementing it

I am working on a small project and I came across that problem.
The project output is a library containing an interface. I would like to implement that interface and seal the functions in it like this if possible:
public interface ITest
{
void SomeMethod();
}
class A : ITest
{
public sealed override SomeMethod()
{
}
}
The idea is to have the interface available to everyone and have some specialized class that implements it. The exception is that I want to make sure that if someone create a specialized class of type A, he/she won't be able to change the method's behavior.
The problem is you can't put the "override" keyword in there since the method isn't declared as "virtual" in the interface. And you can't declare it as "virtual" in the interface since it's not allowed. And you can't remove the "override" keyword since it's needed by "sealed".
Any workaround or brainstorming idea would be welcome, but if someone can come up with a solution that includes an interface, I'd be really happy to learn it!
Thanks!
EDIT: Forget this question! Like Ani said, I forgot that by default method in C# are sealed. Seems like it's always good to go back to the basics once in a while...
I may have completely misunderstood the question, but if your intention is to seal the method in A, you can just do:
class A : ITest
{
public void SomeMethod() { ... }
}
Unlike Java, methods in C# are sealed by default. Subclasses of A won't be able to override the method since it hasn't been marked virtual.
On the other hand, if your intention is to mark the method 'almost sealed' in the interface, so that it forces upon an implementing class to immediately seal it, that isn't possible. It isn't (and shouldn't be) the business of the interface to dictate such details of implementation - an interface is meant to represent a specification.
Use an abstract base class with internal visibility. This base class is not visible outside of the library but allows you to seal the method and the class still implements the interface.
public interface ITest
{
void SomeMethod();
}
internal abstract class SuperA : ITest
{
public abstract void SomeMethod();
}
class A : SuperA
{
public sealed override void SomeMethod()
{
}
}
Your understanding of sealed keyword is incorrect. As a method modifier, sealed is used to prevent a virtual method(defined in the base class) to be override in the next generation of derived classes. For example:
class Base
{
public virtual void M() { }
}
class Derived : Base
{
public sealed override void M() { }
}
class A : Derived
{
public override void M() { } //compile error, M is sealed in Derived
}
Developers can always use new modifier to define a method with the same name in the derived class, that hides the one defined in the base class.
if someone create a specialized class
of type A, he/she won't be able to
change the method's behavior.
If "specialized class" means a class derived from A, the answer is: he can always hide the method in A, but he can't change the method's behavior.
Why not use an abstract class like below.
Haven't tested it but this should work?
public abstract class Test
{
public virtual void SomeMethod() {}
//OR
public abstract void SomeMethod();//MSDN says:
//an abstract method is implicitly virtual
}
class A : Test
{
public sealed override SomeMethod()
{
}
}
Methods in C# are sealed by default.. Here is a sample
class Program
{
static void Main(string[] args)
{
A obj = new A();
obj.SomeMethod();
b ss = new b();
ss.SomeMethod();
Console.ReadLine();
}
}
public interface ITest { void SomeMethod(); }
class A : ITest { public void SomeMethod() {
Console.WriteLine("SomeMethod Called from Class A object");
} }
class b : A
{
//public override void SomeMethod()
//{
// Console.WriteLine("Called from Class B Object");
//}
}

How do I create a method or property in C# that is public, yet not inheritable?

Here is an example. I have two classes, one inherited, and both have a function with the same name, but different arguments:
public class MyClass
{
//public class members
public MyClass()
{
//constructor code
}
public void Copy(MyClass classToCopy)
{
//copy code
}
}
public class InheritedClass : MyClass
{
//public class members
public InheritedClass():base()
{
//constructor code
}
public void Copy(InheritedClass inheritedClassToCopy)
{
//copy code
}
}
My question is how do I make the base class' copy method (MyClass.Copy) non-inheritable or non-visible in InheritedClass? I don't want to be able to do this:
MyClass a;
InheritedClass b;
b.Copy(a);
Does this make sense, or should I keep this functionality in there? Can what I'm asking even be done?
Does this make sense, or should I keep this functionality in there? Can what I'm asking even be done?
Trying to hide a public method like this when used by a base class is problematic. You're purposely trying to violate the Liskov substitution principle.
You can't do what you are wanting to do here; C# does not allow negative variance in inherited members. (almost no languages truly do, actually)
It may be that you don't want an inherited class here at all, though; what you may really want is an interface. Or... your two classes here may not have the correct relationship; perhaps they should both instead be common siblings of a third class, which is their parent.
You can use explicit interface implementation to hide this method from the inheritor. But you will need to add an interface of course and you will need to cast your type to the interface to call your method:
public interface MyInterface
{
void Copy(MyClass classToCopy)
}
public class MyClass : MyInterface
{
void MyInterface.Copy(MyClass classToCopy)
{
//copy code
}
}
This is not possible. An inherited class inherits all public and protected members, methods and properties. Using the sealed modifier with make it non-overridable, but still accessible to your inherited class.
What everyone else said, but if I am inferring your goal correctly, it is to make sure that InheritedClass users never use the MyClass method. In that case, exclude it from MyClass and make two classes that inherit it.
Make MyBaseClass abstract if it should not be instantiated (most likely).
(Edited -- you probably would want to include copy code for anything that's part of the base class in the base class)
public abstract class MyBaseClass
{
public MyClass()
{
//constructor code
}
protected void Copy(MyBaseClass classToCopy)
{
//copy code
}
// other methods that all inherited classes can use
}
public class MyClass: MyBaseClass
{
public MyClass():base()
{
//constructor code
}
public void Copy(MyClass myClassToCopy)
{
base.Copy(myClassToCopy);
//specific copy code for this extensions in this class
}
}
public class InheritedClass : MyBaseClass
{
public InheritedClass():base()
{
//constructor code
}
public void Copy(InheritedClass inheritedClassToCopy)
{
base.Copy(myClassToCopy);
//specific copy code for this extensions in this class
}
}

Categories

Resources