• Have Any Question?
  • contact@eitworld.com

csharp structure





C# Structure

 

  • Structure is a user defined data type that is very similar to the class.
  • Structure is a collection of values of dissimilar and similar data types.
  • Structure are basically used where we have to store complete information for any object like ‘student’ so all the information of a student like student-name, age, class, phone number etc. can be stored in a structure type variable.

Declaration of Structure

 

    • Structure is declared with the use of struct keyword.
    • The basic syntax for a declaration of a structure is as follows:
struct struct_name
{
Data member1;
Data member2;
Data member3;
.
.
.
DatamemberN;
}

    • We can define a struct named as Student as follows:
    • struct Student

 

    • {

 

    • public string name;

 

    • public int age;

 

    • public string branch;

 

    • public string city;

 

    • public string telephone;

 

    • }

 

    • You can create a structure type variable by using following syntax:
Structure_name variable_name;

For example:

student s1;

    • Datamember of structure can be accessed using ‘.’ Or access operator.

For example:

student.name;
student.age;

    • Here is an example which is sufficient for understanding the use of structure:
using System;
namespace structure
{
class struct1
{
struct student //declaration of structure
{
public string name;
public int age;
public string branch;
public string city;
public string telephone;
}
static void Main(string[] args)
{
student s1;//declare structure type variable
//initialization of structure elements
s1.name=”Radha Sharma”;
s1.age=21;
s1.branch=”C.S.”;
s1.city = “Delhi”;
s1.telephone = “9778123545”;
//Accessing structure elements
Console.WriteLine(“Name of student:{0}”, s1.name);
Console.WriteLine(“age of student:{0}”, s1.age);
Console.WriteLine(“Branch of student:{0}”, s1.branch);
Console.WriteLine(“city of student:{0}”, s1.city);
Console.WriteLine(“Telephone number of student:{0}”, s1.telephone);
Console.ReadLine();
}
}
}

  • The output of the above program is as follows:
    Name of student: Radha Sharma
    age of student:21
    Branch of student:C.S.
    city of student:Delhi
    Telephone number of student:9778123545

Features of Structure

 

  • Structures are created quickly and they give faster access of data as compare to classes.
  • Structures are automatically de-allocated once they go out of scope.
  • Structures are value type that’s why these are stored in the stack.
  • Structures can have constructors but not destructors.
  • Structure cannot be inherited.
  • Structure can implement interface.
  • Instance of structure can be created with or without new keyword.
  • Structure can have methods, events and properties like class.


Real Time Web Analytics