Features of C# Structures - CSharp Custom Type

CSharp examples for Custom Type:struct

Introduction

Structures can have methods, fields, indexers, properties, operator methods, and events.

Structures can have constructors, but not destructors.

However, you cannot define a default constructor for a structure. The default constructor of a struct is automatically defined and cannot be changed.

structures cannot inherit other structures or classes.

A structure can implement one or more interfaces.

Structure members cannot be specified as abstract, virtual, or protected.

When you create a struct object using the New operator, it gets created and the appropriate constructor is called.

structs can be instantiated without using the New operator.

classes are reference types and structs are value types

Demo Code

using System;//from w w w  . j  av a  2s  . c o  m
struct Books {
   private string title;
   private string author;
   private string subject;
   private int book_id;
   public void getValues(string t, string a, string s, int id) {
      title = t;
      author = a;
      subject = s;
      book_id = id;
   }
   public void display() {
      Console.WriteLine("Title : {0}", title);
      Console.WriteLine("Author : {0}", author);
      Console.WriteLine("Subject : {0}", subject);
      Console.WriteLine("Book_id :{0}", book_id);
   }
};
public class testStructure {
   public static void Main(string[] args) {
      Books Book1 = new Books();   /* Declare Book1 of type Book */
      Books Book2 = new Books();   /* Declare Book2 of type Book */
      Book1.getValues("C","book2s.com", "C Tutorial",123);
      Book2.getValues("C#","book2s.com", "Tutorial", 1234);
      Book1.display();
      Book2.display();
   }
}

Result


Related Tutorials