Structs vs Classes

I went to lunch with a former co-worker the other day and we got into a conversation about structs vs classes. I have to admit, it has been a while since I looked into them, and I can't really remember the last time I used a struct outside of C++.  I decided to look them back up, and it seems my knowledge on the subject is a bit dated. I knew one main difference was that classes were reference types while structs were values types, but I had no idea that structs could also contain methods.  Here is a quick run down of the two types.

 Struct

  • Value Type
  • Stored on Heap
  • Does not supports Inheritance
  • Cannot have null reference unless set as Nullable
  • Less memory overhead
  • Supports Interfaces
  • Can contain Methods and Events

Classes

  • Reference Type
  • Stored on Stack
  • Supports Inheritance
  • Can be set to Null
  • Larger memory overhead
  • Supports Interfaces
  • Can contain Methods and Events

 

I think this list about sum it all up, but the main difference seems to be that one is a value type while the other is a reference type.

 

String Interpolation

We have all used the good old reliable String.Format() method, but recently I ran across the newer sleeker way of handling strings in C#. It is called "String Interpolation" and it is definitely a shortcut to constructing strings. Although string interpolation is not a new thing in itself, this implementation in C# is rather nice, once you are used to it.

 

Older Method with String.Format()

public static void OldMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = string.Format("Hello World, My Name is {0}, {1}", firstName, lastName);
            Console.WriteLine(formattedString);
}

 

New Method using string interpolation:    

public static void NewMethod()
{
            string firstName = "John";
            string lastName = "Doe";

            var formattedString = $"Hello World, My Name is {firstName}, {lastName}";
            Console.WriteLine(formattedString);
}

 

There is nothing wrong with the older method and personally I still sort of like it.  Pick the best method for your development style and keep on coding.