Skip to content

Instantly share code, notes, and snippets.

@markv12
Last active July 27, 2022 23:05
Show Gist options
  • Select an option

  • Save markv12/ac4040de9abbc9abfb8f08f99b6d92cc to your computer and use it in GitHub Desktop.

Select an option

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);
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(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