Struct vs Class in .Net Framework
Struct vs Class in .Net Framework
Posted by: Rickie Lee http://rickie.cnblogs.com
A struct is a user-defined type that is very similar to a class; it can contain constructors, fields, methods, and properties. Structs are declared using the struct keyword instead of class.
There are some differences between struct and class in .Net Framework.
1. A struct is a value type, whereas classes are reference types. Internally, structs are implicitly derived from System.ValueType.
The following example shows a simple struct declaration:
public struct Book
{
public decimal price;
public string title;
public string author;
}
2. Struct does not support inheritance. A struct can not derive from a class or from another struct. But a class can support inheritance.
3. Structs always contain by default a parameterless, default constructor, which does nothing. You’re allowed to add more overloads, but you can’t add a parameterless constructor. That is to say, structs can declare constructors, but they must take parameters.
4. Although structs are very powerful, they are mainly designed to act as containers for data rather than as fully featured objects. Because they are value types and are stored on the stack, passing them around can be very fast. While classes are reference types and are stored on the Heap.
5. Unlike classes, structs can be instantiated without using a new operator.
References:
1. Beginning ASP.NET 2.0 e-commerce in C# 2005 - Apress
2. MSDN
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?