You are on page 1of 6

Structure Declaration & Object Creation

The keyword struct can be used to declare a structure. The general form of a structure declaration in C# is as follows.         

<modifiers> struct <struct_name>


{
//Structure members
}

Where the modifier can be private, public, internal or public. The struct is the required keyword.

For example  

struct MyStruct
{
public int x;
public int y;
}s

The objects of a strcut can be created by using the new operator as follows.    

MyStruct ms = new MyStruct();

The individual members of a struct can be accessed by using the dot (.) operator as showing below.

ms.x = 10;
ms.y = 20;

Remember that unlike classes, the strcut object can also be created without using the new operator.    

MyStruct ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized. 

Structs & Fields 

A struct in C# can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only
declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields. 

The following is not a valid C# struct and the code will not compile, since the fields inside the structure are trying to initialize.           

struct MyStruct
{
int x = 20; // Error its not possible to initialize
int y = 20; // Error its not possible to initialize
}

using System;
struct MyStruct
{
public int x;
public int y;
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.x = 10;
ms.y = 20;
int sum = ms.x + ms.y;
Console.WriteLine("The sum is {0}",sum);
}
}

However a struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static
fields inside a struct. 

// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
public static int x = 25;
public static int y = 50;
}
class MyClient
{
public static void Main()
{
int sum = MyStruct.x + MyStruct.y;
Console.WriteLine("The sum is {0}",sum);
}

 
Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the struct names. 

Struct & Methods 

A C# struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static
members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.

An example is shown below. 

// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public static void ShowSum()
{
int sum = x + y;
Console.WriteLine("The sum is {0}",sum);
}
}
class MyClient
{
public static void Main()
{
MyStruct ms = new MyStruct();
ms.SetXY(100,200);
MyStruct.ShowSum();
}
}
  
The methods inside a struct can also be overloaded as like inside a class. For example 
// Author:rajeshvs@msn.com 
using System;
struct MyStruct
{
static int x = 25;
static int y = 50;
public void SetXY(int i, int j)
{
x = i;
y = j;
}
public void SetXY(int i)
{
x = i;
y = i;
}
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct();
MyStruct ms2 = new MyStruct();
ms1.SetXY(100,200);
ms2.SetXY(500);
}
}

Structs & Constructors

A C# struct can declare constrcutor, but they must take parameters. A default constructor (constructor without any parameters) are
always provided to initialize the struct fields to their default values. The parameterized constructors inside a struct can also be
overloaded.          

// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
int x ;
int y ; 
{ x = i; y = j;}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
MyStruct ms2 = new MyStruct(30);
ms1.ShowXY();
ms2.ShowXY();
}
}
 
The 'this' operator can also be used in constructors and parameterized constructors can be chained inside a C# constructor. An example
is given below. 

// Author: rajeshvs@msn.com
using System;
struct MyStruct
{
int x ;
int y ;
public MyStruct(int i, int j):this(i+j)
{}
public MyStruct(int i)
{ x = y = i; }
public void ShowXY()
{ Console.WriteLine("The field values are {0} & {1}",x,y); }
}
class MyClient
{
public static void Main()
{
MyStruct ms1 = new MyStruct(10,20);
ms1.ShowXY();
}
}

Finally remember that C# struct do not support destructors. 

Structs & Inheritance 

There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it can't be the base class
for a class. But remember that in C# all types are directly or indirectly inheriting from the super base class object and hence the
structure also. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct
methods. C# struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a
struct declaration. 

Structs & Interfaces 

Just like classes, a C# struct can also implement from an interface. For example         

// Author:rajeshvs@msn.com 
using System;
interface IInterface
{
void Method();
}
struct Complex : IInterface
{
public void Method()
{
Console.WriteLine("Struct Method");
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex();
c1.Method();
}
}

using System;
 
namespace example_struct
{
    class Program
    {
        public struct Student
        {
            int id;
            int zipcode;
            double salary;
 
            // all the members of the struct has to be initialized in this way
            public Student(int id, int zipcode, double salary)
            {
                this.id = id;
                this.zipcode = zipcode;
                this.salary = salary;
            }
 
            // all the members of the struct has to be initialized either in this way
            public Student(int id, int zipcode)
            {
                this.id = id;
                this.zipcode = zipcode;
                this.salary = 3400.00;
            }
 
            // if you left any member of a struct uninitialzed it will give error
            // code below will give error because the zipcode and salary field is left uninitialzed
 
            //public Student(int id)
            //{
            //    this.id = id;
            //}
 
            // struct can also have copy constructor but have to be fully initialzed
            public Student(Student x)
            {
                this.id = x.id;
                this.zipcode = x.zipcode;
                this.salary = x.salary;
            }
 
            public void DisplayValues()
            {
                Console.WriteLine("ID: " + this.id.ToString());
                Console.WriteLine("Zipcode : " + this.zipcode.ToString());
                Console.WriteLine("Salary : " + this.salary.ToString());
            }
        }
 
        static void Main(string[] args)
        {
            Student stu = new Student(12, 201301, 4560.00);
            Student stu1 = new Student(stu);
 
            stu.DisplayValues();
 
            Console.WriteLine("Copy constructor values");
            stu1.DisplayValues();
 
            Console.ReadLine();
        }
}
}

Difference between structs and classes


 
structs classes
 structs are value type  classes are reference type

 structs are stored in stack or a inline  classes are stored on managed heap

 structs doesn't support inheritance  classes support inheritance

 But handing of constructor is different in  Constructors are fully supported in classes


structs. The complier supplies a default no-
parameter constructor, which your are not
permitted to replace

You might also like