Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Reference vs Value types (aka Classes vs Structs) in C#
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { TestClass classA = new TestClass("hello!"); TestClass classB = classA; Console.WriteLine("classA: {0} classB: {1}", classA.GetVal(), classB.GetVal()); TestStruct structA = new TestStruct("hello!"); TestStruct structB = structA; Console.WriteLine("structA: {0} structB: {1}", structA.GetVal(), structB.GetVal()); //here's the main difference: classB.SetVal("new val"); structB.SetVal("new val"); Console.WriteLine(); Console.WriteLine("classA: {0} classB: {1}", classA.GetVal(), classB.GetVal()); Console.WriteLine("structA: {0} structB: {1}", structA.GetVal(), structB.GetVal()); /* Classes are Reference Types, which means when classB is set to classA, you copy classA's POINTER to the value, so when the value is changed all pointers still point there, and they'll get the value's information. In contrast, structs are Value Types, which means they get their own data for every instance. However, they cannot be changed directly (here I used an internal function to change the value), and they cannot be referenced to like classes. */ } } class TestClass //identical structure to TestStruct { string val; public TestClass(string val) { this.val = val; } public void SetVal(string newval) { val = newval; } public string GetVal() { return val; } } struct TestStruct //identical structure to TestClass { string val; public TestStruct(string val) { this.val = val; } public void SetVal(string newval) { val = newval; } public string GetVal() { return val; } } }
run
|
edit
|
history
|
help
0
project euler 18
DateTime Parser
FlagsAttributes - Usage example
gass
MyTime calculation
Ruben
Cells with Odd Values in a Matrix
Intuit // C# // Lecture_4 // Laba_#1
Nullable type - Value Exception - Solution
WhereEnumerator