Structures in CSharp

1. Structure in C# is similar to the class. Just like class, We can encapsulate Fields, Properties, methods in structures.
2. By using Struct Keyword we can declare structure.
3. We can declare struct to represent lightweight objects such as int, enum, double, bool.
4. Struct is a value type.

Below is the example of struct.

+
using System;
 
namespace constructor_example
{
    class Program
    {
        static void Main(string[] args)
        {
            //use of struct 
            Car alto;
            alto.Company = "Maruti Suzuki";
            alto.Model = "Alto K10";
            alto.Year = 2005;
 
            Console.WriteLine();
 
            Console.WriteLine(" Company Name = " + alto.Company);
            Console.WriteLine(" Model Name = " + alto.Model);
            Console.WriteLine(" Launched in Year = " + alto.Year);
 
            //use of Class
            Cars cars = new Cars();
            cars.Company = "Bajaj";
            cars.Model = "xcd";
            cars.Year = 2004;
 
            Console.WriteLine();
 
            Console.WriteLine(" Company Name = " + cars.Company);
            Console.WriteLine(" Model Name = " + cars.Model);
            Console.WriteLine(" Launched in Year = " + cars.Year);
 
            Console.ReadLine();
        }
    }
 
    struct Car
    {
        public string Company;
        public string Model;
        public int Year;
    }
 
    class Cars
    {
        public string Company;
        public string Model;
        public int Year;
    }
}


In above code, I have declared a struct Car with fields like Company, Model, Year. See the syntax of declaring struct is same as class. I have also created class Cars in above example with same fields. You can see the difference there. We don't need to use new keyword while declaring variable of struct, but with class we should have to use new keyword in order to create variable of type class, otherwise compiler will give Object reference not found error.

Difference between Structure and Class
1. Structure is value type, Class is reference type.
2. We can use structure to represent lightweight objects, while classes are used to represent complex objects.
3. All structure elements are public by default, Class variables,constants are private by default.
4. Structures variables can not be initialized at the time of declaration, Class variables can be initialized.
5. Structure elements can't be declared as Protected, Class members can be declared.
6. Structures are not inheritable, Classes are inheritable.
7. Structure doesn't required constructor, Class can require Constructor.


No comments :