feO2x feO2x -3 years ago 88
C# Question

Why is System.Activator visible as a static class in .NET Core?

According to this StackOverflow question, one can use the

Type.IsAbstract
and
Type.IsSealed
properties to determine if a class is static. However, look at the following test:

[Fact]
public void ActivatorNotAbstract()
{
var activatorType = typeof(Activator);

Assert.True(activatorType.IsClass);
Assert.True(activatorType.IsSealed);
Assert.True(activatorType.IsAbstract);
}


This test fails because the last assertion is not true, although
System.Activator
is defined as a static class. This is both true for .NET Core 2.0 (and probably previous versions) as well as .NET 4.5 (and probably other versions, too). You can also find the above test in this GitHub repo.

Why is
Activator
special in this regard?
I couldn't find any other static class in the BCL that would behave this way.

Edit after answer from Camilo

You are right, I didn't look thoroughly - in .NET, the class is actually sealed:

Activator is Sealed in .NET

However, from .NET Core Metadata, it appears to be static:

.NET Core Activator is Static

Now, the actual question should be: why appears
Activator
as a static class in .NET Core (and in NetStandard, too, btw.), but actually is a sealed class?

Answer Source

The issue here is you assumed the following:

although System.Activator is defined as a static class

Interestingly, this is technically correct since the library you compile against defines System.Activator as a static class. This can for example be seen at the source code of the System.Runtime reference assembly or the in a part of the netstandard.dll reference assembly source code.

However, these libraries are meant as a compile-type interface and the actual runtime implementation may derivate a little from this declaration.

In fact, both .NET Core and .NET Framework implement the class as public sealed class Activator (.NET Core) or public sealed class Activator : _Activator (.NET Framework).

This implementation causes IsAbstract to return false.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download