Written by Mark Pringle | Last Updated on Wednesday, December 21, 2022
C# Programming ASP.NET Version: 6.0 General Information
If you are new to ASP.NET C#, you may see undiscernible differences between a class and a struct. On the surface, structures and classes look and behave the same way. However, there are clear differences between these two entities. Let’s examine the differences and similarities while defining each entity.
What is a Class?
A class is a container for characteristics and behaviors specific to an object. It might be likened to a detailed model or blueprint of an object with certain attributes and functionality specific to that object. For instance, a person can be an object. All people have specific characteristics or attributes like age, birthdate, name, height, weight, etc. Also, a person can do certain things like grow older, lose or gain weight, run fast or slow, etc. When combined, these specific attributes and functionalities define a “person.” Similarly, in ASP.NET C# programming, a “class” has specific attributes and behavior or functionality that define it.
In an ASP.NET C# model, a class might look like this:
public class Person
{
public int Id { get; set; }
[Required]
public string? FirstName { get; set; }
[Required]
public string? LastName { get; set; }
public int Age { get; set; }
public int Weight { get; set; }
public int Height { get; set; }
public void GrowOlder()
{
Age++;
}
}
What is a Struct?
A struct in C# is a container that stores values or data and related functionality.
In an ASP.NET C# model, a class might look like this:
public struct Rectangle
{
public int Width;
public int Height;
public Rectangle(int Width, int Height)
{
this.Width = Width;
this.Height = Height;
}
public int Area()
{
return Width * Height;
}
}
The Difference Between Classes and Structures
The key to understanding the difference between a class and a struct is first to realize that in ASP.NET, data types are categorized by how they store their value in memory. Those two categories of types are reference types and value types.
The value type stores its value in its own memory space. The reference type doesn’t store a value in memory. It refers to or points to another memory location that holds the data.
|
Struct |
Class |
|---|---|
|
Structs are value types. |
Classes are reference types. |
|
Structs:
|
Classes
|
|
Examples of Structs are:
|
Examples of Classes are:
|
