C # Programmer's Reference--structure tutorial

Source: Internet
Author: User
Tags constructor copy implement inheritance interface reference
Reference | programs | programmers | tutorials

This tutorial includes two examples. The first example shows you how to declare and use structs, while the second example shows the differences between structs and classes when passing an instance to a method. Also introduces you to the following topics:

    • Structure and class
    • Heap or stack?
    • Constructors and inheritance
    • Properties on the structure

Example 1

This example declares a structure that has three members: a property, a method, and a private field. This example creates an instance of the structure and puts it into use://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 ();
}
}

Output

The stored value is:5

Structure and class

The structure may seem like a class, but there are some important differences that should be brought to the attention. First, the class is a reference type, and the struct is a value type. With structs, you can create objects that behave like built-in types, while enjoying their benefits.

Heap or stack?

When the new operator is invoked on a class, it is allocated on the heap. However, when the structure is instantiated, the structure is created on the stack. This results in a performance gain. Also, you do not handle references to struct instances as you do with classes. You will be working directly on the structure instance. For this reason, when a struct is passed to a method, the struct is passed by value instead of as a reference.

Example 2

This example shows that when a struct is passed to a method, a copy of the struct is passed, and a reference is passed when the class instance is passed. Struct2.cs
Using System;

Class Theclass
{
public int x;
}

struct THESTRUCT
{
public int x;
}

Class TestClass
{
public static void Structtaker (Thestruct s)
{
S.x = 5;
}
public static void Classtaker (Theclass c)
{
c.x = 5;
}
public static void Main ()
{
Thestruct a = new thestruct ();
Theclass B = new Theclass ();
a.x = 1;
b.x = 1;
Structtaker (a);
Classtaker (b);
Console.WriteLine ("a.x = {0}", a.x);
Console.WriteLine ("b.x = {0}", b.x);
}
}

Output

a.x = 1b.x = 5

Code Discussion

The output of this example shows that when a class instance is passed to the Classtaker method, only the value of the class field is changed. However, passing a struct instance to the Structtaker method does not change the structure field. This is because a copy of the structure is passed to the Structtaker method, and a reference to the class is passed to the Classtaker method.

Constructors and inheritance

Structs can declare constructors, but they must take parameters. Declaring a struct's default (parameterless) constructor is incorrect. A struct member cannot have an initializer. Always provide a default constructor to initialize the struct members to their default values.

When you create a struct object by using the New operator, the struct object is created and the appropriate constructor is invoked. Unlike classes, structs can be instantiated without using the NEW operator. If you do not use new, the field remains unassigned and the object is unavailable until all the fields have been initialized.

For structs, there is no inheritance like a class. A struct cannot inherit from another struct or class and cannot be the base of a class. However, structs inherit from base class objects. Structs can implement interfaces and are implemented in exactly the same way that classes implement interfaces. The following is a code fragment of the Structure Implementation interface: interface Iimage
{
void Paint ();
}

struct Picture:iimage
{
public void Paint ()
{
Painting Code goes here
}
private int x, y, Z; Other struct members
}

Properties on the structure

You can customize how the structure is laid out in memory by using attributes. For example, you can use the StructLayout (layoutkind.explicit) and FieldOffset properties to create a layout that is called a union in C + +. Using System.Runtime.InteropServices;
[StructLayout (LAYOUTKIND.EXPLICIT)]
struct testunion
{
[FieldOffset (0)]
public int i;
[FieldOffset (0)]
public double D;
[FieldOffset (0)]
public char C;
[FieldOffset (0)]
public byte B1;
}

In the previous code snippet, all the fields in TestUnion start from the same location in memory.

The following is another example of a field starting at another location that is explicitly set: using System.Runtime.InteropServices;
[StructLayout (LAYOUTKIND.EXPLICIT)]
struct TESTEXPLICIT
{
[FieldOffset (0)]
public long LG;
[FieldOffset (0)]
public int i1;
[FieldOffset (4)]
public int i2;
[FieldOffset (8)]
public double D;
[FieldOffset (12)]
public char C;
[FieldOffset (14)]
public byte B1;
}

I1 and I2 these two int fields share the same memory location as LG. This structural layout control is useful when using platform invoke.

Conclusion

Structures are simple to use and sometimes prove useful. Keep in mind, however, that structs are created on the stack, and that you are not dealing with a reference to a struct, but instead dealing directly with the structure. Structs can be the best choice whenever you need a type that will be used frequently, and in most cases that type is just some data.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.