Overriding method from library - c#

There is a virtual method in a library that my C# project references. How can I override this method in another class within my application?
Example:
namespace TheLibary
{
class SomeClass
{
public virtual void TheMethod()
{
//Do Stuff
}
}
}
Then in my project:
using theLibary;
namespace TheProject
{
class SomeClass
{
public override <Help>
}
}
Edit: Confusion and totally forgetting that this class didn't inherit from the libraries class messed me up, it was late :)

You should study a bit about OOP (and inheritance in particular) before getting down to any serious coding. For quick reference, here’s an example of how to override a method:
namespace TheDll
{
public class SomeClass
{
public virtual void TheMethod()
{ }
}
}
namespace TheProject
{
public class DerivedClass : SomeClass
{
public override void TheMethod()
{ }
}
}
You should observe that the signature of the overriding method (including its name) must be the same. The derived class, on the other hand, may (and typically should, for clarity) be named differently.

Related

How to require an implementation of an abstract class in 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.

Violating polymorphism by having base ViewModel class determine current type?

I have a base ViewModel that has a public method. Things were pretty simple at first and its role was the same for all of its derived classes, but now we want the ViewModel to do different things depending on which derived class calls it.
So for example we have:
public void DoMethod()
{
DoThisMethod();
}
we want something like
public void DoMethod()
{
if (this.GetType().Name == "ThisName")
DoThisMethod();
else
DoAnotherMethod();
}
Is it wrong to do this?
This is a perfect scenario for using Method Overriding.
You should be using OOP concept of method overriding here:
public class BaseViewModel
{
public virtual void DoMethod()
{
DoThisMethod();
}
}
and now when you inherit some class from BaseViewModel, you can define different implement of DerivedViewModel using overrding:
public class DerivedViewModel:BaseViewModel
{
public override void DoMethod()
{
// implementation here
}
}
Now when you will call it using DerivedViewModel object it will the implementation of DoMethod() defined in DerviedViewModel type.
If you don't have access to implementation of BaseViewModel then you will have to use Shadowing Concept:
public class BaseViewModel
{
public void DoMethod()
{
DoThisMethod();
}
}
and in Derived Type:
public class DerivedViewModel:BaseViewModel
{
public new void DoMethod()
{
DoThisMethod();
}
}
But generally it is not considered good to use Shadowing.
You may read more about method overriding in this article
Yes, the solution that you propose is wrong for a design point of view. Your base class should be agnostic of the inherited type "ThisName". Using your naming you could resolve your problem by implementing it in this way:
public class ViewModel
{
public virtual void DoMethod()
{
DoAnotherMethod();
}
public void DoAnotherMethod() {...}
}
public class ThisName: ViewModel
{
public override void DoMethod()
{
DoThisMethod();
}
public void DoThisMethod() {...}
}

Non-virtual, non-abstract method causing "C# virtual or abstract members cannot be private"

Error 1 'Interface.myDerivedClass.myMethod()': virtual or abstract members cannot be private c:\users\igmfun\documents\visual studio 2012\Projects\Interface\Interface\Program.cs 16
Making a virtual or abstract member private would make it inaccessible to other classes, including derived classes, making it impossible to override the method, making its virtual, or abstract quality meaningless. I get it.
But wait... The compiler is complaining about the member in the derived class, not the base class... And I never declared that member as virtual or abstract... so did the overriding member (the one in the derived class) inherit the virtual or abstract quality from the virtual or abstract member it is overriding?
Also, if I change
override void myMethod(){}
to
public override void myMethod(){}
I get a new error,
"No suitable method found to override."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface
{
interface myInterface
{
void myMethod();
}
class myDerivedClass : myInterface
{
override void myMethod()
{
}
}
class Program
{
static void Main(string[] args)
{
}
}
}
The error is somewhat misleading - it looks like compiler tried first to reason locally about code. So it found you are doing override with private (default) specifier. This is clearly an error, but it actually hides the real one - there is nothing to override to start with (you can see that if you change code to public override void myMethod(){}).
Actual fix is to make method public as it implements an interface method:
class MyInterfaceImplementationClass : IMyInterface
{
public void MyMethod()
{
}
}
Alternatively you can explicitly implement the interface too if you prefer method to be not visible from the class directly (similar to private, but you can call by casting to interface):
class MyExplicitInterfaceImplementationClass : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
interface IMyInterface
{
void MyMethod();
}
I think you are confusing Interface with Class.
If you want a base class to derive from use the class keyword not interface
public class BaseClass
{
public void MyMethod()
{
}
}
public class DerivedClass : BaseClass
{
}
If you want to be able to override the method in the base class you can mark it as virtual and use the override keyword in the derived class
public class BaseClass
{
public virtual void MyMethod()
{
}
}
public class DerivedClass : BaseClass
{
public override void MyMethod()
{
// do soothing different
base.MyMethod()
}
}

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");
//}
}

Sealed method in C#

I am a newbie in C#.I am reading about Sealed keyword.I have got about sealed class.I have read a line about Sealed method where we can make Sealed method also.The line was (By declaring method as sealed, we can avoid further overriding of this method.)
I have created a demo but didn't understand that the meaning of above line and sealed method use. Below is my code:-
using System;
namespace ConsoleApplication2
{
class Program:MyClass
{
public override sealed void Test()
{
Console.WriteLine("My class Program");
}
static void Main(string[] args)
{
Program obj = new Program();
obj.Test();
Console.ReadLine();
}
}
class MyClass
{
public virtual void Test()
{
Console.WriteLine("My class Test");
}
}
}
Please tell me why we use Sealed methods and what are the advantages of Sealed methods.
Well, you are testing with only two levels of inheritance, and you are not getting to the point that you're "further overriding" a method. If you make it three, you can see what sealed does:
class Base {
public virtual void Test() { ... }
}
class Subclass1 : Base {
public sealed override void Test() { ... }
}
class Subclass2 : Subclass1 {
public override void Test() { ... } // Does not compile!
// If `Subclass1.Test` was not sealed, it would've compiled correctly.
}
A sealed class is a class which cannot be a base class of another more derived class.
A sealed method in an unsealed class is a method which cannot be overridden in a derived class of this class.
Why do we use sealed methods? What are the advantages of sealed methods?
Well, why do you use virtual methods? To provide a point at which behaviour of a class can be customized. So why do you use sealed methods? To provide a point at which you are guaranteed that no further changes will occur in the behaviour of any derived class with respect to this method.
Points where the behaviour of a class can be customized are useful but dangerous. They are useful because they enable derived classes to change behaviour of the base class. They are dangerous... wait for it... because they enable derived classes to change behaviour of the base class. Virtual methods basically allow third parties to make your classes do crazy things that you never anticipated or tested.
I like writing code that does what I anticipate and what I tested. Sealing a method allows you to continue to allow parts of the class to be overridden while making the sealed methods have guaranteed, testable, stable behaviour that cannot be further customized.
Well, you'd only use "sealed" on a method if you didn't want any derived classes to further override your method. Methods are sealed by default, if they're not declared as virtual and not overriding another virtual method. (In Java, methods are virtual by default - to achieve "default" C# behaviour you have to mark a method as final.)
Personally I like to control inheritance carefully - I prefer whole classes to be sealed where possible. However, in some cases you still want to allow inheritance, but ensure that some methods aren't overridden further. One use might be to effectively template the method, e.g. for diagnostics:
public sealed override void Foo(int x)
{
Log("Foo called with argument: {0}", x);
FooImpl(x);
Log("Foo completed");
}
protected abstract void FooImpl(int x);
Now subclasses can't override Foo directly - they'd have to override FooImpl, so our behaviour will always be executed when other code calls Foo.
The templating could be for other reasons of course - for example to enforce certain aspects of argument validation.
In my experience sealed methods aren't used terribly often, but I'm glad the ability is there. (I just wish classes were sealed by default, but that's another conversation.)
Now if you declare a subclass of Program you won't be able to override the Test method, that's the point.
In most cases you won't need sealed methods but they can prove themselves useful when you're developing a base class for some plugin system that third-party developers have to extend in order to create their own plugin. You can keep some service data like plugin name and whether it is enabled and use sealed methods and properties to do it, so plugin developers won't mess with it. That's one case when sealed members come handy
Sealed Methods
Sealed method is used to define the overriding level of a virtual method.
Sealed keyword is always used with override keyword.
Practical demonstration of sealed method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sealed_method
{
class Program
{
public class BaseClass
{
public virtual void Display()
{
Console.WriteLine("Virtual method");
}
}
public class DerivedClass : BaseClass
{
// Now the display method have been sealed and can;t be overridden
public override sealed void Display()
{
Console.WriteLine("Sealed method");
}
}
//public class ThirdClass : DerivedClass
//{
// public override void Display()
// {
// Console.WriteLine("Here we try again to override display method which is not possible and will give error");
// }
//}
static void Main(string[] args)
{
DerivedClass ob1 = new DerivedClass();
ob1.Display();
Console.ReadLine();
}
}
}
First of all, let's start with a definition; sealed is a modifier which if applied to a class make it non-inheritable and if applied to virtual methods or properties makes them non-ovveridable.
public sealed class A { ... }
public class B
{
...
public sealed string Property { get; set; }
public sealed void Method() { ... }
}
An example of its usage is specialized class/method or property in which potential alterations can make them stop working as expected (for example, the Pens class of the System.Drawing namespace).
...
namespace System.Drawing
{
//
// Summary:
// Pens for all the standard colors. This class cannot be inherited.
public sealed class Pens
{
public static Pen Transparent { get; }
public static Pen Orchid { get; }
public static Pen OrangeRed { get; }
...
}
}
Because a sealed class cannot be inherited, it cannot be used as base class and by consequence, an abstract class cannot use the sealed modifier. It's also important to mention that structs are implicitly sealed.
Example
public class BaseClass {
public virtual string ShowMessage()
{
return "Hello world";
}
public virtual int MathematicalOperation(int x, int y)
{
return x + y;
}
}
public class DerivedClass : BaseClass {
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x - y;
}
public override sealed string ShowMessage()
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior but because it's sealed prevent classes that derive from it to override the method
return "Hello world sealed";
}
}
public class DerivedDerivedClass : DerivedClass
{
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x * y;
}
public override string ShowMessage() { ... } // compile error
}
public sealed class SealedClass: BaseClass {
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x * y;
}
public override string ShowMessage()
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior but because it's sealed prevent classes that derive from it to override the method
return "Hello world";
}
}
public class DerivedSealedClass : SealedClass
{
// compile error
}
Microsoft documentation
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed
C# has it because Java has an identical feature (final methods). I've never seen a legitimate use.
If you don't want to permit extension, the whole class should be marked sealed and not just one method.

Categories

Resources