Overview of Structs in C# (C Sharp)

Structs are yet another type supported by C#. They hold the properties of a value type but they serve the purpose as that of classes. This article will give you an overview of structs with relevant examples.




Like classes, structs can have the following members: fields, constants, properties, methods, constructors, destructors, indexers, operators, events and nested types. Here is a simple example demonstrating the usage of struct:

public struct sampleStruct {
private int member1;
private string member2;
public sampleStruct(int data1, string data2) {
member1 = data1;
member2 = data2;
}
public int PROP1 {
get {
return member1;
}
set {
member1 = value;
}
}
public string PROP2 {
get {
return member2;
}
set {
if (value != null) {
member2 = value;
}
}
}
public int multiply(int data) {
return member1 * data;
}
}

public class sampleClass {
public static void Main() {
sampleStruct obj = new sampleStruct(10, "Have a Nice Day");
sampleStruct obj1 = new sampleStruct();
Console.WriteLine("Members of obj : " + obj.PROP1 + ", " + obj.PROP2);
Console.WriteLine("Members of obj1: " + obj1.PROP1 + ", " + obj1.PROP2);
Console.WriteLine("Initialize obj1 members…");
obj1.PROP1 = 20;
obj1.PROP2 = "Good Day";
Console.WriteLine("Members of obj1: " + obj1.PROP1 + ", " + obj1.PROP2);
int returnValue = obj1.multiply(200);
Console.WriteLine("Multiplying 200 with obj1.member1 gives " + returnValue);
sampleStruct obj2 = new sampleStruct();
Console.WriteLine("Members of obj2: " + obj2.PROP1 + ", " + obj2.PROP2);
sampleStruct[] arrayOfObj = new sampleStruct[3000];
Console.WriteLine("Created 3000 instances of sampleStruct in one go…");

Console.ReadLine();
}
}

Output of this code will be;

Members of obj: 10, Have a Nice Day
Members of obj1: 0,
Initialize obj1 members.
Members of obj1: 20, Good Day
Multiplying 200 with obj1.member1 gives 4000
Members of obj2: 0,
Created 3000 instances of sampleStruct in one go…

Note that default value for a string will be null and hence the console statements printing members of obj1(for the first time) and members of obj2 will print only 0 followed by ,. The string value will not be displayed.

In this example, you have used struct to perform the same function as that of classes. You have used keyword struct instead of class while creating the structure sampleStruct. Inside this structure, you have created two data members, two properties to access these data members, one more method to manipulate on one of the data members.

In addition, you have created a constructor accepting parameters to initialize the data members of structure. Then you have created a class called sampleClass. Inside Main method of sampleClass, you create instances of sampleStruct in multiple ways, as discussed below:

• Create Instance Using new Operator and by Calling Constructor with Parameters: You create instance obj by using new operator and calling constructor defined in sampleStruct with appropriate values. This instance creation code will create the instance obj and initialize values of its data members with the values passed via the constructor

• Create Instance Using new Operator and by Calling Default Constructor: You create instance obj1 by using new operator but you don’t pass any parameters and hence you call the default constructor. Default constructor will initialize all data members of the structure to its default value. Int is assigned with 0 and string is assigned with null. Remember that you cannot override default constructor in structure as you do in classes

• Create Instance Without Using new Operator: Since structure is a value type, you need not instantiate it using new operator. You can simply declare it as you declare any other value types. But ensure that you initialize its data members before using them

• Create Bulk of Objects: You can create bulk of objects in a similar way that you create an array of integers or floating point values. For example, you create an array of integers using the following line of code:

int[] sampleInt = new int[100];
Similarly you can create an array of sampleStruct using the following line of code:
sampleStruct[] obj = new sampleStruct[100];

Though struct looks similar to class, they have ample differences as well. Most important of them is that: Struct is a value type but class is a reference type. This is already discussed. Since structures are value types, they are stored in stack and not in heap. One more important difference is that struct cannot be inherited. However structures are allowed to implement multiple interfaces. This is demonstrated in the following code:

interface ISample1 {
void method1();
}
interface ISample2 {
void method2();
}
struct sampleStruct{
void method1(){
Console.WriteLine(“Implementing Interface ISample1 method”);
}
void method2(){
Console.WriteLine(“Implementing Interface ISample2 method”);
}

}
class sampleClass {
public static void Main() {
sampleStruct obj = new sampleStruct();
obj.method1();
obj.method2();
}
}

Output of this code will be:

Implementing Interface ISample1 method
Implementing Interface ISample2 method

Though structs looks similar to classes, it cannot replace classes at all times. Use them only in performance critical places and in places where the type content looks small enough containing only primitive data members with very less number of instances required. You will be mostly using structures when you deal with offsets and positions.

SetApp - 100 Apps for everything you ever wanted to do on Mac

Add to My Yahoo!


FREE Subscription

Subscribe to our mailing list and receive new articles
through email. Keep yourself updated with latest
developments in the industry.

Name:
Email:

Note : We never rent, trade, or sell my email lists to
anyone. We assure that your privacy is respected
and protected.

Visit .NET Programming Tutorial Homepage

______________________________________________________

Recommended Resource

| How Do You Establish Polymorphism in C# (C Sharp) | How Do You Overload == Operator in C# (C Sharp) ? | How Do You Overload == Operator in C# (C Sharp) ? | How to Perform User Defined Conversions Between Structures (Struct) | Illustration of C# (C Sharp) Keywords (params, ref, out) Used to Declare | Introduction to Static Classes of C# (C Sharp) | Introduction to Static Members of C# ( C Sharp) | Overview of Structs in C# (C Sharp) | Using Constructors and Destructors in C# (C Sharp) |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2019 - All Rights Reserved.