Reputation: 9
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)
{
}
}
}
Upvotes: 0
Views: 1837
Reputation: 43616
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()
}
}
Upvotes: 1
Reputation: 100547
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();
}
Upvotes: 3