Home > Backend Development > C++ > Can C# Enums Inherit from Other Enums?

Can C# Enums Inherit from Other Enums?

DDD
Release: 2025-01-26 07:16:12
Original
576 people have browsed it

Can C# Enums Inherit from Other Enums?

“Inheritance” of enums

In C#, enumerations cannot inherit from other enumerations. This is due to the way enumerations are implemented in the CLI, all enumerations must derive from the System.Enum base class.

Enumeration syntax that looks like it is inherited from another enumeration is actually a change in the way the underlying value of the enumeration is represented, not true inheritance. For example:

<code class="language-c#">namespace low
{
    public enum Base
    {
        X, Y, Z
    }
}

namespace mid
{
    public enum Consume : Base
    {
        // 隐式继承 Base 的值
    }
}</code>
Copy after login

This syntax can be misleading because it implies that Consume inherits from Base. However, in reality, Consume is still a separate enumeration that inherits from System.Enum.

This behavior is clearly defined in section 8.5.2 of the CLI specification:

  • All enumerations must be derived from System.Enum.
  • As mentioned above, all enumerations are value types and therefore sealed (cannot be inherited).

Therefore, it is not possible in C# to create a class or enumeration that actually inherits the value of another enumeration.

The above is the detailed content of Can C# Enums Inherit from Other Enums?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template