{"id":757,"date":"2024-12-15T12:45:38","date_gmt":"2024-12-15T18:45:38","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=757"},"modified":"2024-12-15T12:46:33","modified_gmt":"2024-12-15T18:46:33","slug":"structs-in-c-net-dotnet","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/structs-in-c-net-dotnet\/","title":{"rendered":"Structs in C# .Net (dotnet)"},"content":{"rendered":"\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Definition<\/h2>\n\n\n\n<p>In C#, a struct (short for structure) is a value type used to encapsulate related data and behavior into a single, lightweight object. Structs are often used when you need to represent simple data objects that do not require the overhead of a class.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Features of Structs<\/h3>\n\n\n\n<ol>\n<li><strong>Value Type<\/strong>:\n<ul>\n<li>Structs are stored on the <strong>stack<\/strong>, unlike classes, which are reference types and stored on the <strong>heap<\/strong>.<\/li>\n\n\n\n<li>When a struct is assigned to a new variable, a <strong>copy<\/strong> of the value is created, not a reference.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Lightweight<\/strong>:\n<ul>\n<li>Designed for scenarios where you need small data objects that are allocated and deallocated quickly.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>No Inheritance<\/strong>:\n<ul>\n<li>A struct <strong>cannot inherit<\/strong> from another struct or class.<\/li>\n\n\n\n<li>However, a struct can implement <strong>interfaces<\/strong>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Default Constructor<\/strong>:\n<ul>\n<li>Structs do not allow explicit parameterless constructors.<\/li>\n\n\n\n<li>The compiler provides a <strong>default constructor<\/strong> that initializes all fields to their default values (e.g., <code>0<\/code> for integers, <code>false<\/code> for booleans).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Immutability (Recommended)<\/strong>:\n<ul>\n<li>While structs can have mutable fields, it&#8217;s recommended to design structs as <strong>immutable<\/strong> for better performance and consistency.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Declaring a Struct<\/h3>\n\n\n\n<p>Here&#8217;s an example of defining and using a struct:<\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#5E69FF\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-php\">public struct Point\n{\n    public int X { get; set; }\n    public int Y { get; set; }\n\n    \/\/ Constructor to initialize the fields\n    public Point(int x, int y)\n    {\n        X = x;\n        Y = y;\n    }\n\n    \/\/ Method to calculate the distance from another point\n    public double DistanceTo(Point other)\n    {\n        return Math.Sqrt(Math.Pow(X - other.X, 2) + Math.Pow(Y - other.Y, 2));\n    }\n}\n\n\/\/ Usage\nclass Program\n{\n    static void Main()\n    {\n        Point p1 = new Point(3, 4);\n        Point p2 = new Point(0, 0);\n\n        Console.WriteLine($\"Distance: {p1.DistanceTo(p2)}\");  \/\/ Output: Distance: 5\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Differences Between Structs and Classes<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th><strong>Struct<\/strong><\/th><th><strong>Class<\/strong><\/th><\/tr><\/thead><tbody><tr><td><strong>Type<\/strong><\/td><td>Value type<\/td><td>Reference type<\/td><\/tr><tr><td><strong>Memory Allocation<\/strong><\/td><td>Stored on the stack<\/td><td>Stored on the heap<\/td><\/tr><tr><td><strong>Inheritance<\/strong><\/td><td>Cannot inherit other types<\/td><td>Can inherit from classes<\/td><\/tr><tr><td><strong>Default Constructor<\/strong><\/td><td>Compiler-provided<\/td><td>User-defined allowed<\/td><\/tr><tr><td><strong>Performance<\/strong><\/td><td>Faster for small objects<\/td><td>More suitable for large, complex objects<\/td><\/tr><tr><td><strong>Nullability<\/strong><\/td><td>Cannot be null unless wrapped in <code>Nullable&lt;T&gt;<\/code><\/td><td>Can be null<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use a Struct<\/h3>\n\n\n\n<p>Use a struct when:<\/p>\n\n\n\n<ul>\n<li>You need a small, simple data object.<\/li>\n\n\n\n<li>The object is immutable (values don&#8217;t change after creation).<\/li>\n\n\n\n<li>You care about performance and want to avoid heap allocations.<\/li>\n\n\n\n<li>You don\u2019t need inheritance.<\/li>\n<\/ul>\n\n\n\n<p>Example scenarios:<\/p>\n\n\n\n<ul>\n<li>Representing points, colors, or complex numbers.<\/li>\n\n\n\n<li>Simple containers like <code>KeyValuePair<\/code> or <code>Tuple<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Common Examples in .NET<\/h3>\n\n\n\n<p>C# and .NET use structs for several built-in types:<\/p>\n\n\n\n<ul>\n<li><strong>Primitive types<\/strong> like <code>int<\/code>, <code>float<\/code>, <code>double<\/code>, <code>bool<\/code>.<\/li>\n\n\n\n<li><strong><code>System.DateTime<\/code><\/strong> for dates and times.<\/li>\n\n\n\n<li><strong><code>System.TimeSpan<\/code><\/strong> for time intervals.<\/li>\n\n\n\n<li><strong><code>System.Guid<\/code><\/strong> for globally unique identifiers.<\/li>\n<\/ul>\n\n\n\n<p>Structs are efficient and powerful for specific use cases where simplicity and performance are critical.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Definition In C#, a struct (short for structure) is a value type used to encapsulate related data and behavior into a single, lightweight object. Structs are often used when you need to represent simple data objects that do not require the overhead of a class. Key Features of Structs Declaring a Struct Here&#8217;s an example [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":468,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[53,23,54],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/757"}],"collection":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/comments?post=757"}],"version-history":[{"count":1,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/757\/revisions"}],"predecessor-version":[{"id":758,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/757\/revisions\/758"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/468"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=757"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=757"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=757"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}