I read somewhere
"Abstract and Sealed modifiers are equivalent to a class which is static"
I also found that
"When you declare a static class, internally the compiler marks the class abstract and sealed, and creates a private constructor in the IL code"
so, I decided to do this:
static class A
{
public static void test()
{
Console.WriteLine("test");
}
}
Now, the class "A" cannot be inherited nor instantiated.
So, let us write a class B
using abstract
to prevent instantiation and using sealed
to prevent inheritance.
But, this approach fails.
which should be equivalent to
public abstract sealed class B
{
private B()
{
}
public void test()
{
Console.WriteLine("test");
}
}
But I recieve an error stating "error CS0418:
B': an abstract class cannot be sealed or static"` . Any ideas why this is not possible ?
Thanks in advance for your answers.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
Yes, abstract class can have Static Methods. The reason for this is Static methods do not work on the instance of the class, they are directly associated with the class itself.
Abstract classes cannot be instantiated, but they can be subclassed.
As static class is sealed, so no class can inherit from a static class. We cannot create instance of static class that's the reason we cannot have instance members in static class, as static means shared so one copy of the class is shared to all. Static class also cannot inherit from other classes.
Having checked the IL of the System.Directory class (which is static), it is declared in IL as:
.class public auto ansi abstract sealed beforefieldinit System.IO.Directory
extends System.Object
{
...
Further, this article (http://msdn.microsoft.com/en-us/library/ms229038.aspx) suggests that the CLR handles static classes as abstract sealed classes to support languages that do not support directly delcaring static classes (eg C++).
Thus in conclusion, static classes in C# are syntactic sugar for sealed abstract classes with private constructors. I for one am glad of that as "static" is a lot easier to write and a lot easier to get right.
By definition a sealed
class enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
Abstract
keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
(Source: http://msdn.microsoft.com/en-us/library/ms173150.aspx)
This would imply that any class marked abstract would not be able to be sealed, since you wouldn't be able to derive it anywhere.
The code you mentioned doesn't make any sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With