Hi Guys
NP42 struct and class
Following website says structs are lightweight classes. Therefore in my view of class can be used instead of struct.
Is there any situation only struct can be used? Anyone knows please tell me. It is much appreciated if it is demonstrated with example.
http://www.albahari.com/value%20vs%20reference%20types.html
Thank you
Thank you very much for help, Alan
OK, just a small one then :)
using System;
class Test{ static void Main() { Test t = new Test(); t.Go(); Console.ReadLine(); }
public void Go() { MyStruct x = new MyStruct(); Console.WriteLine(x.a); // 0 DoSomething(ref x); Console.WriteLine(x.a); // 3 } public void DoSomething(ref MyStruct pValue) { pValue.a = 3; }}
public struct MyStruct{ public long a, b, c, d, e, f, g, h, i, j, k, l, m;}
This program illustrates two points:
1. If you call the default constructor of a struct, then all the fields are set to their default values which, in the case of 'a', is zero.
2. If you pass a struct variable by reference to a method, then any changes made to the struct within the method are preserved when the method returns.
If you now change the Test class to the following:
public void Go() { MyStruct x = new MyStruct(); Console.WriteLine(x.a); // 0 DoSomething(x); Console.WriteLine(x.a); // 0 } public void DoSomething(MyStruct pValue) { pValue.a = 3; }}
The struct is now passed by value to DoSomething() and so the changes are not preserved when the method returns.
Thank you for explanation, Alan
Please support with a complete program as well.
It's an error to give the fields of a struct values when they're declared. For example this would be an error:
public struct MyStruct
{
long a = 1, b, c, d, e, f, g, h, i, j, k, l, m;
}
because 'a' has been given a value.
However, the way Matthew has it is fine because no fields are being given values.
It is an error to initialize an instance field in a struct. But in the following website struct has been initialized. Please explain the reason.
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory2B01142006125918PM/csharp_memory2B.aspx
long a, b, c, d, e, f, g, h, i, j, k, l, m;
Please support with the complete program as well.
When creating your own types, you can always use a class instead of a struct.
However, structs are generally more efficient for objects which only have a memory footprint of a few bytes, which are created frequently and in large numbers and don't need to support inheritance. This is because, unlike classes, structs can be allocated on the stack rather than the heap which is faster and requires no overhead. Also objects allocated on the stack don't need to be garbage collected.
This is why in the .NET framework commonly used types such as Int32, Int64, Char, Boolean, Double, Point and DateTime are implemented as structs rather than classes.