Structure's


Structure's

  • This concept is not new in C#; it is taken from C language.
  • In C language‘s structures, you can write only some member variables, called as "data members" / "fields". But in C#‘s structures, you can write fields along with some methods also.
  • So, In C#, structures are almost all similar to the classes, but having some differences with the classes.

Difference Between Classes and Structures

Classes

Structures

Declared with "class" keyword. Declared with "struct" keyword.
Can contain fields, methods, constructors, destructors, properties etc. Can contain fields, methods, constructors, destructors, properties etc.
Supports inheritance. Doesn’t support inheritance.
User-defined default constructor can be implemented. User-defined default constructor can‘t be implemented.
Data Members can be initialized in the class definition. Data members can‘t be initialized in the structure definition.

Implementation :

  1. Define structure
    
       struct structurename
       {
         //fields
         //methods
       }
    
    
  2. Create instance for structure
    
       structurename instancename = new structurename();
    
    

C# Coding on Structures :


 namespace StructuresDemo
 {
  struct Employee
  {

   //fields
   private int EmployeeID;
   private string EmployeeName;
   private double Salary, Tax, NetSalary;
  
   //methods
   public void ReadData()
    {
     Console.Write("Enter Employee ID: ");
     EmployeeID = Convert.ToInt32(Console.ReadLine());
     Console.Write("Enter Employee Name: ");
     EmployeeName = Console.ReadLine();
     Console.Write("Enter Salary: ");
     Salary = Convert.ToDouble(Console.ReadLine());
    }

    public void Calculate()
     {
      Tax = Salary * 10 / 100;
      NetSalary = Salary - Tax;
     }

    public void DisplayData()
     {
      Console.WriteLine("\n\nEmployee ID: " + EmployeeID);
      Console.WriteLine("Employee Name: " + EmployeeName);
      Console.WriteLine("Salary: " + Salary);
      Console.WriteLine("Tax: " + Tax);
      Console.WriteLine("Net Salary: " + NetSalary);
     }
   }

  class Program
   {
    static void Main(string[] args)
     {
      //create structure instance
      Employee e = new Employee();
    
      //call the methods
      e.ReadData();
      e.Calculate();
      e.DisplayData();
      Console.Read();
     }
   }
 }
Tag : C#, C# Tutorials
0 Komentar untuk "Structure's"

Back To Top