ASPCode.net logo
  • Home 
  • Blogs 
  • Tags 
Blog
  1. Home
  2. Articles
  3. C# OOP - Structs

C# OOP - Structs

Posted on July 1, 2024  (Last modified on October 11, 2024) • 2 min read • 305 words
C#
 
Oop
 
C#
 
Oop
 
Share via
ASPCode.net
Link copied to clipboard

Video is in Swedish

Sure, here’s a short article on C# OOP - Structures:

Structures in C# are value types that can be used to represent simple data types such as integers, floating-point numbers, and characters. They are similar to classes but have some key differences.

Here are the main features of structures in C#:

  1. Value Type: Structures are value types, which means they are stored on the stack instead of the heap like reference types (classes). This makes them faster and more efficient.
  2. No Inheritance: Structures cannot inherit from other classes or structs. They can only inherit from their parent struct.
  3. No Constructor Overloading: Structures do not support constructor overloading, which means you can’t define multiple constructors with different parameters.
  4. No Destructors: Structures do not have destructors like classes.

Here’s an example of how to declare and use a structure in C#:

public struct Person
{
    public string Name;
    public int Age;

    public void PrintInfo()
    {
        Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Declare a new instance of the Person struct
        Person person = new Person();

        // Set the properties of the structure
        person.Name = "John";
        person.Age = 30;

        // Call the PrintInfo method on the structure
        person.PrintInfo();
    }
}

In this example, we declare a Person struct with two properties: Name and Age. We then create an instance of the Person struct and set its properties. Finally, we call the PrintInfo method on the structure to print out the name and age.

Structures are useful when you need to represent simple data types that don’t require inheritance or complex behavior. They can be used as parameters in methods, returned from methods, and stored in arrays or collections. However, they should be used sparingly and only when necessary, as they have some limitations compared to classes.

Video  

Swedish

 C# Advanced - SOLID
C# OOP - UML - Class Diagram 
Follow me

I code in Java, C#, Golang, SQL and more

     
© 2024 Systementor AB
ASPCode.net
Code copied to clipboard