Console C#.Net Tutorial

Visual Studio.NET IDE

Define C#.NET

C# Comment

C# Variables

C# Data Types

C# Escape Sequence

C# Operators

Format String

Operator Precedence

C# Keywords

Constant Variable

Type Conversion

Flow Control

C# Arrays

C# Character

C# Strings

User-Define Methods

Variable Scope

C# Enumerations

C# Structure

C# Exception Handling

Object Oriented Programming

C# Classes

Constructor & Destructor

C# Inheritance

C# Polymorphism

C# Operator Overloading

C# Method Overriding

C# Interface

Abstract Classes & Methods

Sealed Classes, Methods

C# Properties

C# Indexer

C# Delegates

C# Generics

C# Collection

C# ArrayList

C# Stack

C# Queue

C# HashTable

C# SortedList

Page Stats

Visitor: 187

C#.Net Structures

A structure is a User defined data type in which different data elements can be stored. A structure can be used to represent a set of attributes like employee code, employee name, designation, salary, date of joining etc.

A structure can be instantiated without using the new keyword and in that case the default values will not be assigned. If you want to use properties, methods or events, you must initialize the struct with the new keyword.

Example 1: Use of structure and class

struct Struct1
{
    public int Value;
}
class Class1 
{
    public int Value;
}
class Test
{
    static void Main()
    {
        Struct1 v1 = new Struct1();
        Struct1 v2 = v1;
        v2.Value = 123;
        Class1 r1 = new Class1();
        Class1 r2 = r1;
        r2.Value = 123;
        Console.WriteLine("Values: {0}, {1}", v1.Value, v2.Value);
        Console.WriteLine  ("Refs: {0}, {1}", r1.Value, r2.Value);
    }
}
Output: Values: 0, 123 Refs: 123, 123
Advertisement

Similarity between Structures and Classes

Structure data type Class data type
A structure is a derived data type or constructed data type. A class is also a derived data type or constructed data type
A structure can contain constructors, constants, fields, methods, properties, indexers, operators, and nested types as its members. A class can also contain constructors, constants, fields, methods, properties, indexers, operators, and nested types as its members.

Comparison between Structures and Classes

Structure data type Class data type
A structure is a value type so it is faster than a class object. A class is reference type.
A structure is lightweight object. A class is not a lightweight object.
It is an error to declare a default (parameterless) constructor for a structure. However, it can have parametrized constructors. It is not an error to declare a default (parameterless) constructor for a class.
Member variables of a structure are allocated default values only if new keyword is used otherwise they are not allocated values. Member variables in a class are always allocated default values.