Skip to content

Instantly share code, notes, and snippets.

@markv12
Last active July 27, 2022 23:05
Show Gist options
  • Save markv12/ac4040de9abbc9abfb8f08f99b6d92cc to your computer and use it in GitHub Desktop.
Save markv12/ac4040de9abbc9abfb8f08f99b6d92cc to your computer and use it in GitHub Desktop.
using System;
namespace ClassVsStructDemo
{
class Program
{
static void Main(string[] args)
{
DemoStruct struct1 = new DemoStruct();
struct1.x = 4;
DemoStruct struct2 = struct1;
ref DemoStruct struct3 = ref struct2; //struct2 and struct3 point to the same memory
IInterfaceDemo struct4 = new DemoStruct(1, 5); //this struct is treated as a reference type
DemoStruct struct5; //This struct is initialized by hand without using "new"
struct5.x = 1;
struct5.y = 2;
struct5.structArray = null;
struct5.childObject = null;
struct5 = GetModifiedStruct(struct5);
DemoStruct? struct6 = null; // '?' means nullable version of this struct
if(struct6 != null) { /*This will not run */ }
struct6 = new DemoStruct();
if (struct6.HasValue) //struct6 != null and struct6.HasValue are functionally equivalent
{
DemoStruct struct7 = struct6.Value; // .Value throws an exception if .HasValue is false
struct7.x = 1; //struct7 is a regular non-nullable struct
}
DemoClass object1;
DemoClass object2;
object1 = new DemoClass(0);
object2 = object1;
ModifyObject(object2);
}
private static void ModifyObject(DemoClass objectToModify)
{
objectToModify.x += 5;
}
private static DemoStruct GetModifiedStruct(DemoStruct structToModify)
{
structToModify.x += 5;
return structToModify;
}
}
public struct DemoStruct : IInterfaceDemo
{
//public DemoStruct() //Doesn't compile
//{
// x = 5;
// y = 5;
// structArray = new DemoStruct[999];
// childObject = new DemoClass(2);
//}
//public DemoStruct(float _x) //Doesn't compile
//{
// x = _x;
//}
public DemoStruct(float _x, float _y)
{
x = _x;
y = _y;
structArray = null;
childObject = null;
}
public float x;
public float y;
public DemoStruct[] structArray;
//public DemoStruct childStruct; //Doesn't compile
public DemoClass childObject;
public void InterfaceMethod() { /* DoStuff */ }
}
public class DemoClass : IInterfaceDemo
{
public DemoClass(float _x)
{
x = _x; //Doesn't assign all the member variables
}
public float x;
public float y;
public DemoStruct[] structArray;
public DemoStruct childStruct;
public DemoClass childObject;
public void InterfaceMethod() { /* DoStuff */ }
}
public interface IInterfaceDemo
{
public void InterfaceMethod();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment