A struct type is a value type that contain the
value in the stack. A struct is a simple user-defined type.
Struts support access modifiers, constructors,
constants, fields, methods, properties, indexers, operators, events etc.
- Structure cannot be inherited and we can say they are sealed.
- Structure is implicitly inherit from System.ValueType.
- The default constructor of a structure initializes each field to a default value.
- You cannot replace the default constructor of a structure.
- You cannot define destructor in Structure.
- Structs can be inherited from an interface.
public struct Student
{
public int Id;
public int Name;
public double Age;
}
namespace StructDisplay
{
public class ProgramStruct
{
public struct Student
{
public int Id;
public string Name;
public double Age;
public Student(int Id, string Name, double Age)
{
this.Id = Id;
this.Name = Name;
this.Age = Age;
}
public void DisplayValues()
{
Console.WriteLine("Id: " + this.Id.ToString());
Console.WriteLine("Name :
" + this.Name.ToString());
Console.WriteLine("Age : " + this.Age.ToString());I
}
}
static void Main(string[] args)
{
Student stuobjl = new Student(786, "Anil
Singh", 28);
stuobjl.DisplayValues();
Console.ReadLine();
}
}
}
The
Output as given below
Id:
786
Name:
Anil Singh
Age:
28
How Struct
can be inherited from an interface?
Example for implementation to struct can be
inherited from an interface
namespace StructUsinglnterface
{
public class Program
{
public interface Ii
{
void DisplayValues();
public struct Student : Ii
{
int Id;
string Name;
int Age;
public Student(int Id, string Name, int Age)
{
this.Id = Id;
this.Name = Name;
this.Age = Age;
}
public void DisplayValues()
{
Console.WriteLine("Id: " + this.Id.ToString());
Console.WriteLine("Name : " + this.Name.ToString());
Console.WriteLine("Age : " + this.Age.ToString());
Console.WriteLine("Age : " + this.Age.ToString());
}
}
static void Main(string[] args)
{
Student student = new Student(786, "Anil
Singh", 28);
student.DisplayValues();
student.DisplayValues();
Console.ReadLine();
}
}
}
}
The
Output as given below.
Id:
786
Name:
Anil Singh
Age:
28