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 { public class
sampleClass { Console.ReadLine(); Output of this code will be; Members of
obj: 10, Have a Nice Day 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 int[] sampleInt
= new int[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 { } Output of this code will be: Implementing
Interface ISample1 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.
|