Struct, properties of structs in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 2451 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Polymorphism, method overloading and overriding in C# before this article.

Introduction

So far, we have learnt polymorphism in C#. Now let's see what is a struct and its description with example in this chapter.

Background

The main objective of this article is to learn about structs with example in C# programming.

Struct

In C#, we have structures (value type) which are used to encapsulate the small groups of variables such as specifications of a device etc. To create a structure, we have to use struct keyword. 
Example,
public struct Mobile
{
    public string Brand;
    public string Model;
    public decimal Cost;
    public string OS;
}
The above example shows a declaration of simple struct Mobile. In that we declared specifications of the mobile such as its Brand, Cost, Model, OS (Operating System) etc.
  1. Struct is a type definition which uses the similar syntax of class.
  2. Structs can be instantiated without using new operator.
  3. When a struct is assigned to a new variable, it will get fill with the data and doesn't allow to change any newly modified data to the original one.
  4. We can use struct as a nullable type and can be assigned a null value.
  5. Structs can implement one or more interfaces.
  6. Structs cannot have abstract, protected and virtual members.

Struct vs Class


StructClass
It is a value type.It is a reference type.
It doesn't support inheritance.It supports inheritance.
Structs cannot have a parameter-less constructor.Class can have a parameter-less constructor.
It cannot have Virtual membersClasses supports virtual members.
No finalizers are supported.Can have finalizers.

Struct Constructors

Similar to class, we can build a constructor for struct. For this, we must follow the below points,
  • Structs cannot have a parameter-less constructor. i.e,
    struct MyStruct
    {
        int a;
        public MyStruct()  // Error: doesn't support parameter-less constructor
        {
            ........;
        }
    }
  • We said above that structs cannot support a parameter-less constructor. But we can have a parameter-less constructor that can't be overridden implicitly. This performs the bit-wise zeroing of its fields or parameters. 
  • We must assign each and every field (which we have declared in the struct) explicitly while we define a constructor to struct. Example,
    struct MyStruct
    {
        int a;
        int b;
        public MyStruct(int i, int j) // Must assign both fields
        { 
            this.a = i;
            this.b = j;
        }
    }
  • We cannot have field initializers in struct as we do in a class. Example,
    struct MyStruct
    {
        int a = 5; // Error: We cannot initialize a field in struct
    }
  • Field initialization is possible in class. i.e,

  • class MyClass
    {
        int a = 5; // This doesn't give error.
    }
  • Structs can also contain methods, constants, fields, properties, operators, indexers, nested types and events.

  • Struct members cannot be declared as protected because struct cannot support inheritance.

Lets have a simple example code of using struct,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        struct Mobile
        {
            public string Name;
            public string Color;
            public bool Availability;
            public long Cost;
        };

        static void Main()
        {
            Mobile Apple;                   // Create struct.
            Apple.Name = "iphone 5s 16gb";
            Apple.Color = "Gold";
            Apple.Availability = true;
            Apple.Cost = 35999;

            Console.WriteLine(Apple.Name);  // Prints Name
            Console.WriteLine(Apple.Color); // Prints color

            if (Apple.Availability == true) // Condition for availability status.
            {
                Console.WriteLine("In Stock...You can buy it for INR " + Apple.Cost);
            }
            else
            {
                Console.WriteLine("Out of Stock...Sorry");
            }
        }
    }
}
In the above example, we have a struct Mobile with fields Name, Color, Availability and Cost. In the Main method, we have created an object on the stack without using any new operator.

We have also implemented a simple logic (if/else condition) to check the status of availability. And if it is available, we are showing the cost of the Mobile in the console like below,


Conclusion

In this article, we have studied about structs in C# programming language with example. Hope you understand.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read Interface, Explicit Interface Implementations in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)