-
C# Namespaces
Wednesday, March 4, 2020
In large programs or if you’re using third-party libraries, you’ll often encounter types with the same name as your own. In order to avoid such naming collisions, you can namespace your types. A namespace is simply a grouping of related code under a single name. In our previous articles on C#, you’ll notice we used: using System; Console.WriteLine("Hello"); However, this isn’t the fully qualified name for the WriteLine method. The full name is System.…more
-
C# Generics
Sunday, March 1, 2020
Imagine that you created a method that accepts an array of numbers and loops over them and writes the value at each index to the console. Now imagine you wanted similar functionality, but applied to an array of doubles, strings or booleans. Now, you can’t use your original method because it only accepts numbers so you have two alterntives: You could create a method that does the same thing for each type.…more
-
C# Interfaces
Thursday, February 27, 2020
An interface defines a contract that specifies what methods a class must implement in order to satisfy that contract. Any class that implements an interface is guaranteed to have those methods or the code will not compile. Creating an interface is similar to creating a class or a struct: public interface IFileReader { void Read(string filename); } As you probably notice, the interface does not implement the method, it only declares it.…more
-
C# Structs
Thursday, February 20, 2020
Structs and Classes are constructed very similarly in C#: struct Book { private string title; private int[] editions; public string Title { get { return title; } set { title = value; } } public string Author { get; set; } public int[] Editions { get { return editions; } set { editions = value; } } public string Blurb() { return $"{Title} by {Author}"; } } And they are instantiated in the same way:…more
-
C# Autoimplemented Properties
Wednesday, February 19, 2020
In object-oriented programming, you’ll often be creating getters and setters for instance variables. For example: class Book { private string title; public Book(string title) { this.title = title; } GetTitle() { return title; } SetTitle(string title) { this.title = title; } } The problem with this is that it’s verbose and creating getters and setters is extremely common so it becomes a little cumbersome. Now, you might be thinking “If I can just freely get and set the instance variable, why not make its accessibility public?…more