Structure(Struct)
structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
Classes and Structures have the following basic differences:
- classes are reference types and structs are value types.
- structures do not support inheritance.
- structures cannot have default constructor.
Use When :
- It logically represents a single value, similar to primitive types (int, double, etc.).
- It has an instance size under 16 bytes.
- It is immutable. (No Change)
- It will not have to be boxed frequently
8) Class vs Struct
When to Use Struct :
1. Small
2. Logically an immutable value (no Change)
3. There's a lot of them
Differences:
classes are reference types
static void Main(string[] args)
{
MyClass myclass = new MyClass();
myclass.I = 3;
MyClass myClass2 = myclass;
myclass.I = 4;
Console.WriteLine("Class : {0},{1}", myclass.I, myClass2.I);
MyStruct myStruct = new MyStruct();
myStruct.I = 3;
MyStruct myStruct2 = myStruct;
myStruct.I = 4;
Console.WriteLine("Struct : {0},{1}", myStruct.I, myStruct2.I);
myclass.J = 3;
myclass.ClassMod(myclass);
myStruct.J = 3;
myStruct.StructMod(myStruct);
Console.WriteLine("{0},{1}", myclass.J, myStruct.J);
Console.ReadLine();
}
public class MyClass
{
public int I;
public int J;
public void
ClassMod(MyClass mc)
{
mc.J += 100;
Console.WriteLine(mc.J);
}
}
public struct MyStruct
{
public int I;
public int J;
public void
StructMod(MyStruct ms)
{
ms.J += 100;
Console.WriteLine(ms.J);
}
}
Result :
Class : 4,4
Struct : 4,3
103
103
103,3
No comments:
Post a Comment