Creating a struct

Structs are defined by using the struct keyword:


public struct PostalAddress
{
    // Fields, properties, methods and events go here...
}

Structs share most of the same syntax as classes.

Within a struct declaration, fields cannot be initialized unless they are declared as const or static.

A struct may not declare a default constructor (a constructor without parameters) or a destructor.

When a struct is assigned to a new variable, all the data is copied.

Any modification to the new copy does not change the data for the original copy.

Structs are value types and classes are reference types.

Structs can be instantiated without using a new operator.

Structs can declare constructors that have parameters.

A struct cannot inherit from another struct or class.

A struct cannot be the base of a class.

All structs inherit directly from System.ValueType, which inherits from System.Object.

Structs can implement interfaces.

Structs can be used as a nullable type and can be assigned a null value.

A struct is a value type and it doesn't support inheritance and virtual members.

The struct cannot have finalizer.

The following code creates a struct version of the Rectangle.


using System;

struct Rectangle{
   int Width;
   int Height;
   
}

class Test
{
    static void Main()
    {
        Rectangle r = new Rectangle();

    }
}

If you define a constructor for a struct you must use the constructor to initialize all fields.


using System;

struct Rectangle
{
    int Width;
    int Height;

    public Rectangle()
    {
        Width = 0;
        Height = 0;
    }
} 

class Test
{
    static void Main()
    {
        Rectangle r = new Rectangle();

    }
}

struct cannot have the field initializer.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.