Monday, 11 July 2016

What is a structure in C#?What are the differences between a class and structure?

In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
Classes and Structures have the following basic differences:
  • classes are reference types and structs are value types.
  • structures do not support inheritance.
  • structures cannot have default constructor.
public struct Book
{
    public decimal price;
    public string title;
    public string author;
}
------------------------------------
// struct1.cs
using System;
struct SimpleStruct
{
    private int xval;
    public int X
    {
        get 
        {
            return xval;
        }
        set 
        {
            if (value < 100)
                xval = value;
        }
    }
    public void DisplayX()
    {
        Console.WriteLine("The stored value is: {0}", xval);
    }
}

class TestClass
{
    public static void Main()
    {
        SimpleStruct ss = new SimpleStruct();
        ss.X = 5;
        ss.DisplayX();
    }
}

No comments:

Post a Comment