Difference between struct and class in C#

Difference between struct and class in C#

?

1. Definition:

  • A struct is a value type, while a class is a reference type.

?

2. Memory Allocation:

  • Structs are typically allocated on the stack, while classes are allocated on the heap.

?

3. Default Behaviour:

  • Structs are value types and are copied by value, while classes are reference types and are copied by reference.

?

4. Inheritance:

??? Structs do not support inheritance, while classes support single inheritance.

?

5. Nullability:

  • Structs cannot be null unless they are wrapped in a nullable type, while classes can be assigned a null value.

?

6. Performance:

  • Structs are generally more efficient in terms of memory and performance for small, simple data types, while classes provide more flexibility and are better suited for complex data and behaviour.

?

7. Usage:

  • Use structs for small, lightweight objects that represent simple data types, such as coordinates, colours, or key-value pairs.
  • Use classes for more complex objects that require behaviour, encapsulation, and inheritance, such as entities in an object-oriented design.

?

8. Example:

???// Struct example

   public struct Point
   {
       public int X;
       public int Y;
   }
 

   // Class example

   public class Person
   {
       public string Name;
       public int Age;
   }        
Diya Arora

A seeker of great opportunities ?

4 个月

Nice explanation sir ??

回复

要查看或添加评论,请登录

Vikram .的更多文章

  • Generics and Collections in C#

    Generics and Collections in C#

    Generics and collections are fundamental concepts that are extensively used to create reusable and type-safe code for…

    1 条评论
  • Primitive Types and Non-Primitive Types in C#

    Primitive Types and Non-Primitive Types in C#

    Primitive Types: 1. Primitive types in C# are the most basic data types that are directly supported by the language and…

    3 条评论

社区洞察

其他会员也浏览了