Why does this C# class declaration compile? - c#

This question really is kinda pointless, but I'm just curious:
This:
public sealed class MyClass
{
protected void MyMethod(){}
}
compiles, but gives a warning
while This:
public sealed class MyClass
{
public virtual void MyMethod(){}
}
doesn't compile. Just out of sheer curiosity, is there a reason for this?

virtual is used to declare a method/property "override-able".
sealed is used to declare that class cannot be inherited from.
So a virtual method in a sealed class could never be overridden, as the class could never be inherited from. It just doesn't make sense.
protected affects access to a member, it does not declare it "override-able" as virtual does (though it is often used in that manner) and is accordingly not contradictory.

The only reason I can think of is that sometimes you would need to write protected methods to override other protected methods. The language could have been designed to allow this:
protected override void Foo()
but not this
protected void Foo()
but that might have been seen to be a little hard to follow - it's the absence of override which makes it useless, whereas in the case of
public virtual void Foo()
it's the presence of virtual that is useless. The presence of something "wrong" is probably easier to understand than the absence of something useful.
In this case, being virtual may also have performance implications, whereas making something protected instead of private probably doesn't - so it's a bit more severe.
These are just guesses though really - if we're really lucky, Eric Lippert will give a more definitive answer. He's the one you want, not me :)
Best answer: treat warnings as errors and they're equivalent anyway ;)

I can't see a good reason for this. The protected MyMethod can be called from MyClass, but will never be called from a derived class (because MyClass is sealed). The virtual version is also allowed to be called directly from MyClass, but it is illegal for the method to have an override because you can't derive a class from MyClass...

A sealed class can have protected members via inheritance.
When a method is part of a class, it doesn't matter how that method got there.
In the first case, with the protected method on the sealed class, its the same as if the sealed class inherited a protected method. So it compiles.
Out of curiosity, what exactly is the warning given?

The error is:
CS0549: 'function' is a new virtual member in sealed class 'class'.
First of all, despite the fact that it doesn't really make sense to include new protected or virtual members in a sealed class, the CLI¹ does allow it. The CLI also allows calling members of a sealed class using the callvirt IL instruction, even though a compiler could freely replace it with the call instruction.
Currently, I can't find anything in ECMA-334 (C# Language Specification) that requires the compiler emit the above error. It appears like a Microsoft's implementation added the error just because it doesn't make sense to include new virtual members in a sealed class.
¹The CLI is a virtual machine, and the C# compiler emits byte code that runs on it. Almost any concept that's illegal in the CLI is also illegal in C# for that reason - but this is a case where C# does a little extra (not that it's a problem).
Edit: It seems to posts getting marked up are explaining why it doesn't make sense to write code like that in the OP. But regarding what rule made it a compiler error they appear to be wrong.

A sealed class cannot be sub-classed, therefore virtual is not an option. Thus error.
This first is a bit silly but valid, thus warning.

I'd guess the compiler does some optimizations with sealed classes that are impossible if you have a virtual method declared - "not having a vtable" seems a likely candidate.
That's just a guess, though.

As sealed When applied to a class, the sealed modifier prevents other classes from inheriting from it.
here i am trying to explain you one by one:
public sealed class MyClass
{
protected void MyMethod(){}
}
it gives you warning because practically it make no sense because after declaring a class as sealed you can't inherits it and as your method is protected so you can't access it outside the class using it's object(and keep also in mind that you can't create a child class of this so you can't use this method by that trick also).So practically it makes no sense to making it protected so compiler gives you a warning but if you make it as public or internal then it will not gives you error because it's useful in that case.
now the second one:
public sealed class MyClass
{
public virtual void MyMethod(){}
}
as you sealed you class and now you are making your method as virtual so indirectly you are giving a offer to someone to override it and that can be only possible by inheritance and here comes the issue.That you class is sealed so you can't perform inheritance with this class.so that's why with virtual it gives error.
i hope it will help you to understand.
for reference http://msdn.microsoft.com/en-us/library/88c54tsw.aspx

Declaring a new protected member implies an intent to share that member with descendent classes. A sealed class cannot have descendents, so declaring a new protected member is a bit of an oxymoron, just as declaring a new virtual method in a sealed class.
As for why virtual produces an error while protected only produces a warning, I can only speculate that perhaps it has to do with the fact that new virtual methods require the compiler to build data structures for the type (a vtable), whereas new protected members only have an access flag set - no new data structure. If the compiler is prohibited from creating a vtable for a sealed class, what should it do if it encounters a new virtual method? Fail the compile. A new protected method in a sealed class is pointless but doesn't required the compiler to venture into forbidden territory.

Related

Why is it required to have override keyword in front of abstract methods when we implement them in a child class?

When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
public abstract class Person
{
public Person()
{
}
protected virtual void Greet()
{
// code
}
protected abstract void SayHello();
}
public class Employee : Person
{
protected override void SayHello() // Why is override keyword necessary here?
{
throw new NotImplementedException();
}
protected override void Greet()
{
base.Greet();
}
}
Since the method is declared abstract in its parent class it doesn't have any implementation in the parent class, so why is the keyword override necessary here?
When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
"Why?" questions like this can be hard to answer because they are vague. I'm going to assume that your question is "what arguments could be made during language design to argue for the position that the override keyword is required?"
Let's start by taking a step back. In some languages, say, Java, methods are virtual by default and overridden automatically. The designers of C# were aware of this and considered it to be a minor flaw in Java. C# is not "Java with the stupid parts taken out" as some have said, but the designers of C# were keen to learn from the problematic design points of C, C++ and Java, and not replicate them in C#.
The C# designers considered overriding to be a possible source of bugs; after all, it is a way to change the behaviour of existing, tested code, and that is dangerous. Overriding is not something that should be done casually or by accident; it should be designed by someone thinking hard about it. That's why methods are not virtual by default, and why you are required to say that you are overriding a method.
That's the basic reasoning. We can now go into some more advanced reasoning.
StriplingWarrior's answer gives a good first cut at making a more advanced argument. The author of the derived class may be uninformed about the base class, may be intending to make a new method, and we should not allow the user to override by mistake.
Though this point is reasonable, there are a number of counterarguments, such as:
The author of a derived class has a responsibility to know everything about the base class! They are re-using that code, and they should do the due diligence to understand that code thoroughly before re-using it.
In your particular scenario the virtual method is abstract; it would be an error to not override it, and so it is unlikely that the author would be creating an implementation by accident.
Let's then make an even more advanced argument on this point. Under what circumstances can the author of a derived class be excused for not knowing what the base class does? Well, consider this scenario:
The base class author makes an abstract base class B.
The derived class author, on a different team, makes a derived class D with method M.
The base class author realizes that teams which extend base class B will always need to supply a method M, so the base class author adds abstract method M.
When class D is recompiled, what happens?
What we want to happen is the author of D is informed that something relevant has changed. The relevant thing that has changed is that M is now a requirement and that their implementation must be overloaded. D.M might need to change its behaviour once we know that it could be called from the base class. The correct thing to do is not to silently say "oh, D.M exists and extends B.M". The correct thing for the compiler to do is fail, and say "hey, author of D, check out this assumption of yours which is no longer valid and fix your code if necessary".
In your example, suppose the override was optional on SayHello because it is overriding an abstract method. There are two possibilities: (1) the author of the code intends to override an abstract method, or (2) the overriding method is overriding by accident because someone else changed the base class, and the code is now wrong in some subtle way. We cannot tell these possibilities apart if override is optional.
But if override is required then we can tell apart three scenarios. If there is a possible mistake in the code then override is missing. If it is intentionally overriding then override is present. And if it is intentionally not overriding then new is present. C#'s design enables us to make these subtle distinctions.
Remember compiler error reporting requires reading the mind of the developer; the compiler must deduce from wrong code what correct code the author likely had in mind, and give an error that points them in the correct direction. The more clues we can make the developer leave in the code about what they were thinking, the better a job the compiler can do in reporting errors and therefore the faster you can find and fix your bugs.
But more generally, C# was designed for a world in which code changes. A great many features of C# which appear "odd" are in fact there because they inform the developer when an assumption that used to be valid has become invalid because a base class changed. This class of bugs is called "brittle base class failures", and C# has a number of interesting mitigations for this failure class.
It's to specify whether you're trying to override another method in the parent class or create a new implementation unique to this level of the class hierarchy. It's conceivable that a programmer might not be aware of the existence of a method in a parent class with exactly the same signature as the one they create in their class, which could lead to some nasty surprises.
While it's true that an abstract method must be overridden in a non-abstract child class, the crafters of C# probably felt it's still better to be explicit about what you're trying to do.
Because abstract method is a virtual method with no implementation, per C# language specification, means that abstract method is implicitly a virtual method. And override is used to extend or modify the abstract or virtual implementation, as you can see here
To rephrase it a little bit - you use virtual methods to implement some kind of late binding, whereas abstract methods force the subclasses of the type to have the method explicitly overridden. That's the point, when method is virtual, it can be overridden, when it's an abstract - it must be overriden
To add to #StriplingWarrior's answer, I think it was also done to have a syntax that is consistent with overriding a virtual method in the base class.
public abstract class MyBase
{
public virtual void MyVirtualMethod() { }
public virtual void MyOtherVirtualMethod() { }
public abstract void MyAbtractMethod();
}
public class MyDerived : MyBase
{
// When overriding a virtual method in MyBase, we use the override keyword.
public override void MyVirtualMethod() { }
// If we want to hide the virtual method in MyBase, we use the new keyword.
public new void MyOtherVirtualMethod() { }
// Because MyAbtractMethod is abstract in MyBase, we have to override it:
// we can't hide it with new.
// For consistency with overriding a virtual method, we also use the override keyword.
public override void MyAbtractMethod() { }
}
So C# could have been designed so that you did not need the override keyword for overriding abstract methods, but I think the designers decided that would be confusing as it would not be consistent with overriding a virtual method.

Why does C# support abstract overrides of abstract members?

Whilst browsing through some legacy code, I was surprised to encounter an abstract override of a member that was abstract by itself. Basically, something like this:
public abstract class A
{
public abstract void DoStuff();
}
public abstract class B : A
{
public override abstract void DoStuff(); // <--- Why is this supported?
}
public abstract class C : B
{
public override void DoStuff() => Console.WriteLine("!");
}
Isn't the distinction between a virtual or abstract member always available to the compiler? Why does C# support this?
(This question is not a duplicate of What is the use of 'abstract override' in C#? because the DoStuff-method in class A is not virtual but abstract as well.)
To clarify the question: the question is not "why is an abstract override legal?" An existing question handles that. (See also my blog post on the subject.)
Rather, the question is "why is an abstract override legal when the overridden method is also abstract?"
There are several arguments in favour of not giving an error here.
It's harmless.
To give an error, someone on the compiler team must have thought of this scenario and considered it to be worth the time to design the feature, verify that it doesn't cause any bad interactions with other features, write a detailed specification, implement it, test it, write the documentation, translate the error message into two dozen languages, translate the documentation, and maintain the feature forever. What's the compelling benefit that justifies those costs? I see none.
Whenever something looks weird in C# ask yourself what if the base class was owned by someone not on my team and they like to edit it?
Consider for example a variation on your scenario:
public abstract class Z
{
public abstract void DoStuff();
}
public class A : Z
{
public override void DoStuff()
{
throw new NotImplementedException();
}
}
public abstract class B : A
{
public override abstract void DoStuff();
}
The authors of class A realize that they have made a mistake and A and DoStuff should be abstract. Making a class abstract is a breaking change because anyone who says "new A()" is now wrong, but they verify that none of their client teams in their org have created a new A. Similarly, calling base.DoStuff is now wrong. But again, there are none.
So they change their code to your version of class A. Should class B now have a compile time error? Why? There's nothing wrong with B.
Many features of C# that seem odd are there because the designers consider the brittle base class to be an important scenario.
Finally, we should consider what the preconditions are for overriding a method. The overridden method has to be accessible by the overriding code, the overriding code has to be in a derived type, and the overridden method has to be a virtual method in the first place. There are obvious good reasons for those requirements. Introducing another requirement -- overrides require that no more than one of the overriding and overridden method be abstract -- doesn't have a principled reason underlying it.

Preventing a C# subclass from overwriting a method

Say I have an abstract parent class called "Parent" that implements a method called "DisplayTitle". I want this method to be the same for each subclass that inherits "Parent" - I would like a compile error if a subclass attempts to implement their own "DisplayTitle" method. How can I accomplish this in C#. I believe in Java, I'd just mark the method as "final", but I can't seem to find an alternative in C#. I've been messing around with "sealed" and "override", but I can't get the behavior that I'm looking for.
For example, in this code:
using System;
namespace ConsoleApplication1
{
class Parent
{
public void DisplayTitle() { Console.WriteLine("Parent's Title"); }
}
class ChildSubclass : Parent
{
public void DisplayTitle() { Console.WriteLine("Child's Own Implementation of Title");
}
static void Main(string[] args)
{
ChildSubclass myChild = new ChildSubclass();
myChild.DisplayTitle();
Console.ReadLine();
}
}
}
I'd like to receive a compile error saying that the "ChildSubClass" can't override "DisplayTitle". I currently get a warning - but it seems like this is something that I should be able to do and I don't know the proper attributes to label the method.
How can I accomplish this in C#. I believe in Java, I'd just mark the method as "final", but I can't seem to find an alternative in C#.
The rough equivalent is sealed in C#, but you normally only need it for virtual methods - and your DisplayTitle method isn't virtual.
It's important to note that ChildSubclass isn't overriding DisplayTitle - it's hiding it. Any code which only uses references to Parent won't end up calling that implementation.
Note that with the code as-is, you should get a compile-time warning advising you to add the new modifier to the method in ChildSubclass:
public new void DisplayTitle() { ... }
You can't stop derived classes from hiding existing methods, other than by sealing the class itself to prevent the creation of a derived class entirely... but callers which don't use the derived type directly won't care.
What's your real concern here? Accidental misuse, or deliberate problems?
EDIT: Note that the warning for your sample code would be something like:
Test.cs(12,19): warning CS0108:
'ConsoleApplication1.ChildSubclass.DisplayTitle()' hides inherited
member 'ConsoleApplication1.Parent.DisplayTitle()'. Use the new keyword
if hiding was intended.
I suggest you turn warnings into errors, and then it's harder to ignore them :)
A derived class cannot override your method, you didn't declare it virtual. Note how that's very different in C# compared to Java, all methods are virtual in Java. In C# you must explicitly use the keyword.
A derived class can hide your method by using the same name again. This is probably the compile warning you are talking about. Using the new keyword suppresses the warning. This method does not in any way override your original method, your base class code always calls the original method, not the one in the derived class.
Use the sealed modifier to prevent subclasses from overriding your classes, properties, or methods. What isn't working when you use sealed?
http://msdn.microsoft.com/en-us/library/88c54tsw.aspx
I'm fairly certain that what you want is not possible in C# using method modifier keywords.
Sealed only applies when overriding a virtual method in an ancestor class, which then prevent further overriding.

'Protected member in sealed class' warning (a singleton class)

I've implemented a singleton class and keep getting the warning that a method I'm writing is a 'new protected member declared in a seal class.' It's not affecting the build but I don't really want to ignore the warning in case it causes problems later on? I understand a sealed class is a class that cannot be inherited - so it's methods cannot be overridden, but I still don't get why the following code would give me the warning (is it due to the use of the singleton design?):
namespace WPFSurfaceApp
{
public sealed class PresentationManager
{
PresentationManager()
{
}
protected void MethodName()
{
}
public static PresentationManager Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly PresentationManager instance = new PresentationManager();
}
}
EDIT: The warning is regarding MethodName() method.
EDIT: Change public void MethodName() to protected void MethodName()
The warning is because protected does not make sense in a class that can't be inherited from. It will logically be exactly the same as private for a sealed class.
It's not an error, per se, but the compiler is trying to draw your attention to the fact that making it protected instead of private will provide you no benefit and may not be doing what you intended (if you intended it to be visible to a sub-class, which can't exist in a sealed class).
So, yes, you can safely ignore it, but it's logically inconsistent to have protected members in a sealed class.
MSDN Entry for Compiler Warning CS0628
It is obvious because it doesn't make any sense. What will be use of protected member if class cant be inherited
As MSDN Says
Types declare protected members so that inheriting types can access or
override the member. By definition, you cannot inherit from a sealed
type, which means that protected methods on sealed types cannot be
called.
Think about when you review code yourself. You see something that makes no sense as far as you can see. There are a few likely possibilities:
The developer has done something foolish.
The developer has done something too clever for its purpose to be obvious to you.
The developer did something reasonable that no longer makes sense due to changes that took place in the mean time.
The developer did something that makes no sense yet, but will if a planned change happens.
In the first case, they should fix it.
In the second case, they should document it.
In the third case, they should change it; it'll make little practical difference but the code will make more sense and it may have some minor performance benefit.
In the fourth case, they should document it for the time being, and either make that change or back out of it sooner rather than later.
Either way, you would want to discuss it with them.
It's the same here, it makes no sense to add a protected member to a sealed class. I've no idea why you did it, and can't decide which of the four cases above applies, but one of them does. The warning highlights this. Do whichever of the four actions applies according to which of the four cases is in effect.
I say your are playing with C#. Seriously !!
In a static class, it is said that we can't declare protected members as static classes cannot be instantiated. In fact, when we write protected members in static classes it will throw an error during the build.
In a sealed class, it will throw a warning during the build. I guess like static classes, sealed classes should also give an ERROR and not a WARNING. If this difference should be there then why?

WHy should virtual methods be explicitly overridden in C#?

Why should virtual methods be explicitly overridden in C#?
By declaring a method as virtual, you are stating your intention that the method can be overridden in a derived class.
By declaring your implementing method as override, your are stating your intention that you are overriding a virtual method.
By requiring that the override keyword be used to override a virtual method, the designers of the language encourage clarity, by requiring you to state your intentions.
If you don't add the override keyword, the method will be hidden (as if it had the new keyword), not overridden.
For example:
class Base {
public virtual void T() { Console.WriteLine("Base"); }
}
class Derived : Base {
public void T() { Console.WriteLine("Derived"); }
}
Base d = new Derived();
d.T();
This code prints Base.
If you add override to the Derived implementation, the code will print Derived.
You cannot do this in C++ with a virtual method. (There is no way to hide a C++ virtual method without overriding it)
It is because the C# team members are all skilled C++ programmers. And know how incipient this particular bug is:
class Base {
protected:
virtual void Mumble(int arg) {}
};
class Derived : public Base {
protected:
// Override base class method
void Mumble(long arg) {}
};
It is a lot more common then you might think. The derived class is always declared in another source code file. You don't typically get this wrong right away, it happens when you refactor. No peep from the compiler, the code runs pretty normal, just doesn't do what you expect it to do. You can look at it for an hour or a day and not see the bug.
This can never happen in a C# program. Even managed C++ adopted this syntax, breaking with native C++ syntax intentionally. Always a courageous choice. IntelliSense takes the sting out the extra verbiage.
There's a lot of syntax tweaks in C# that resemble this kind of bug avoidance syntax.
EDIT: and the rest of the C++ community agreed and adopted the override keyword into the new C++11 language specification.
Because it makes code more readable:
class Derived : Base
{
void Foo();
}
In C++, Foo may or may not be a virtual method, we can't tell by looking at the definition. In C# we know a method is virtual (or isn't) because there is either a virtual or override keyword.
Jason's comment below is a better answer.
(edited for clarity)
Not all virtual methods should be overridden, though all abstract methods should (and must) be. As for why the 'override' keyword is explicit, that's because overriding and hiding behave differently. A hiding method is not called through a reference to a base class, whereas an overridden method is. This is why the compiler specifically warns about how you should use the 'new' keyword in the case where you are hiding rather than overriding.

Categories

Resources