Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from struct

Tags:

I am try to figure out what is the problem whit my code. I have this code:

public struct MyStructA
{
    public MyStructA(string str)
    {
        myString= str;
    }

    public string myString;
}

public struct MyStructB: MyStructA
{
    public string myReversString;
}

And i get this error:

Error at compile time: Type 'MyStructA' in interface list is not an interface

I don't understand why? the .net not implemnet struct like class?

like image 753
user2110292 Avatar asked Mar 14 '13 11:03

user2110292


People also ask

Can you inherit from a struct C#?

Structs don't provide inheritance. It is not possible to inherit from a struct and a struct can't derive from any class. Similar to other types in . NET, struct is also derived from the class System.

Can you inherit structs in C++?

Yes. The inheritance is public by default.


2 Answers

A struct Is Implicitly Sealed

According to this link:

Every struct in C#, whether it is user-defined or defined in the .NET Framework, is sealed–meaning that you can’t inherit from it. A struct is sealed because it is a value type and all value types are sealed.

A struct can implement an interface, so it’s possible to see another type name following a colon, after the name of the struct.

In the example below, we get a compile-time error when we try to define a new struct that inherits from the one defined above.

public struct PersonName
{
    public PersonName(string first, string last)
    {
        First = first;
        Last = last;
    }

    public string First;
    public string Last;
}

// Error at compile time: Type 'PersonName' in interface list is not an interface
public struct AngryPersonName : PersonName
{
    public string AngryNickname;
}
like image 153
One Man Crew Avatar answered Nov 14 '22 07:11

One Man Crew


Struct does not support inheritance, if you need you have to use class, see msdn

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do.

like image 40
Adil Avatar answered Nov 14 '22 08:11

Adil