C # struct

Source: Internet
Author: User

Brief introduction

C/c++ programmers are more or less using struct c++ Span style= "font-family: the song Body;" > struct and Span style= "font-family: ' Times New Roman ';" >class c# struct and class struct

Why do I need a struct?

As we all know, there is no struct concept in java , so why does C # introduce a struct ? The most basic reason is that you can create types of value types so that you have better performance in a managed environment.

Differs from java , c# ) Span style= "font-family: the song Body;" > Instances of reference types are allocated on the heap, reclaimed by the garbage collector when objects are not referenced, instances of value types are allocated on the stack, and memory is reclaimed when they leave their scope. The value type itself stores the value itself, the reference type stores the reference, c# string

In C # , a struct is a value type,class is a reference type, and can be passed by enum and struct keyword to create an object of value type. Using value types reduces the number of objects on the managed heap, reduces the burden on the garbage collector (GC) , improves performance, and has a significant disadvantage: the overhead of passing large objects by value types is expensive, boxing, and unboxing affect performance.

Classes and structs

  Public structemployeestruct {Private int_foonumber;  PublicEmployeestruct (intfoonumber): This() {_foonumber=Foonumber; }         Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public stringGetMessage () {return string. Format ("{0}--{1}", Name, age); }    }

As you can see from the above,structs and classes are very similar, but they still have essential differences, and then we analyze them all.

1. Structs and inheritance

StructsfromSystem.ValueTypeInheritance andClassesinherit fromSystem.Objector fromSystem.Objectother types of inheritance, of courseSystem.ValueTypealso fromSystem.ObjectInheritance(that's not the point .). Structsinterfaces can be implemented, but not from anotherClasses,structsinherited, and cannot be used as otherClassesthe base class. You know, when you putstructswhen used as an interface, an invisible boxing occurs because the interface is a reference type. Take a look at the following code:

struct foo:ifoo{       intnew Foo ();

An instance of Foo is created and assigned to IFoo ( boxing ), which is actually used when the IFoo is called Foo the instance after boxing.

2. Constructors

Although the CLR allows, it is not allowed to define a parameterless constructor in structs . For value types, the compiler does not generate a default constructor by default, nor does it call the default constructor, so the C # compiler does not allow the consumer to define a parameterless constructor. The field cannot be initialized because structs does not generate a default constructor. The following (error):

Struct myfoo{        int1;}

Remember that the compiler puts the initialization work in the constructor and cannot initialize the field because structs does not have a default constructor.

Interestingly, you can use the following syntax:

Foo foo = new Foo ();

The previous section learned that although the Initialize foo uses the new operator, the structs instance is assigned to the stack. New Foo () does not call the parameterless constructor, only the fields that initialize the struct are the default values.

struct foo{       int  x;         Public Foo (int  x)       {           this. x= x;       }}    Foo Foo  =  new foo ();

Note that I have overloaded the constructor, but I am able to call new Foo ().

3. Destructors

Structs does not allow the definition of destructors, if you throw to define a destructor, the compiler will immediately prompt an error, but Structs can implement IDisposable Interface.

4. Comparison against NULL

Structs cannot be compared with null , which is no longer a problem in . NET framework2.0 (nullable type), and is beyond the scope of this article for nullable types.

5. readonly keyword

For reference types, ReadOnly prevents you from assigning a value to a variable, but does not prevent you from modifying the state of the current reference object. For value types,readonly is a bit like the const keyword in c + + , which prevents you from modifying the Reference object, and also means that he cannot be assigned a value. This causes the reinitialization to occur once. Take a look at the following code:

     Public classMyreferencetype { Public intState {Get;Set; } }     Public structMyValueType { Public intState {Get;Set; } }    Public voidTestMethod () {Myreferencetype=NewMyreferencetype ();//ErrorMyreferencetype.state =1234;//OkMyValueType=NewMyValueType ();//ErrorMyvaluetype.state =1234;//Error}

The variables for the foreach statement and the using statement are implicitly readonly, so if you use structs, you cannot change its state.

When to use structs

The difference between classes and structs is clear from the previous description , so let 's take a look at the scenario for using structs :

L instance uses a primitive type like C #

L need to create a large number of short-lived instances ( For example, in the loop body )

L instances do not require a large number of passes

L do not need to inherit from other types or do not want to be inherited by other types

L want to be manipulated copy of your instance

Scenarios that are not suitable for use with structs :

L instances are too large, and when instances are too large, passing instances can be costly. Microsoft recommends that the ideal size of the structs should be below 16bytes

L When the back is caused by boxing, unpacking operation. About packing, unpacking beyond the scope of this article

C # struct

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.