The difference between structure and class in C #

Source: Internet
Author: User
Tags comparison

Directory

Comparison of instances between classes and structs

The difference between class and structure

How to select a structure or class

A Example comparison of classes and structs:

Structure Example:

public struct Person
{
string Name;
int height;
int weight
public bool overWeight()
{
//implement something
}
}

class Example:

public class TestTime
{
int hours;
int minutes;
int seconds;
public void passtime()
{
//implementation of behavior
}
}
Call Procedure:

public class Test
{
public static ovid Main
{
Person Myperson=new Person //声明结构
TestTime Mytime=New TestTime //声明类
}
}

As we can see from the example above, the declaration of a class is very similar to that of a struct, except that the qualifier is the difference between struct and class, and the method of defining a new structure and defining a new class is very similar when used. So what is the specific difference between a class and a structure?

Two. Differences in class and structure

1. Value type and reference type

Structs are value types: value types assign addresses on the stack, all base types are struct types, for example: int corresponds to SYSTEM.INT32 structure, string corresponds to System.String structure, you can create more value types by using structs

Class is a reference type: A reference type assigns an address on the heap

The execution efficiency of the stack is higher than that of the heap, but the stack has limited resources and is not suitable for dealing with large logically complex objects. So the struct handles a small object treated as a base type, while a class handles a business logic

Because structs are value types, assignments between structs can create new structures, while classes are reference types, and assignments between classes are just copies of references

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.