C# OOP - Structs
Posted on July 1, 2024 (Last modified on October 11, 2024) • 2 min read • 305 wordsVideo 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#:
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.
Swedish