Skip to content

Instantly share code, notes, and snippets.

@matt123miller
Forked from mandarinx/SmEntry.cs
Created March 31, 2016 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matt123miller/6e09805f5ce53ee12feca373d9aac61a to your computer and use it in GitHub Desktop.
Save matt123miller/6e09805f5ce53ee12feca373d9aac61a to your computer and use it in GitHub Desktop.
C# generics example

Hi Anton!

In the SmEntry file, you'll see an example of how you could implement your (previously) struct as a generic class. The part tells the compiler that you want to specify a type upon construction of the class, and that the type is limited to the interface IOptionsItem. Check out the documentation for more info on generic constraints. https://msdn.microsoft.com/en-us/library/d5x73970.aspx

The constructor of SmEntry accepts an instance of the same type specified by the class. If the constraint hadn't been an interface, you could do a content = new T(); in the constructor to let the class instantiate a new instance of the specified type.

You'll also see two example classes that implements the interface accepted by SmEntry. With a setup like this, you can let SmEntry only hold objects of a certain type, and since it's an interface, you can slap that on multiple classes, which gives you more architectural freedom than relying on inheritance. Now we're venturing into the realm of inheritance and interfaces, which is a whole field in its own, and totally out of scope for this example.

In the SmEntryTest file, you'll see how I use the generic class. On lines 9 and 13, I create two variables of type SmEntry<OptionsItem> and SmEntry<OtherItem>. This tells the SmEntry class to set the content field type to OptionsItem and OtherItem.

There are lots of classes in C# that uses generics, like a List and a Dictionary<T, U>. By learning to use generics, you can solve a lot of common problems really easy.

using UnityEngine;
public interface IOptionsItem {}
public class OptionsItem : IOptionsItem {
override public string ToString() {
return "OptionsItem";
}
}
public class OtherItem : IOptionsItem {
override public string ToString() {
return "OtherItem";
}
}
public class SmEntry<T> where T : IOptionsItem {
private T content;
public SmEntry(T instance) {
content = instance;
}
public T Content {
get { return content; }
}
}
using UnityEngine;
using System.Collections;
public class SmEntryTest : MonoBehaviour {
void Awake() {
OptionsItem opts = new OptionsItem();
SmEntry<OptionsItem> optEntry = new SmEntry<OptionsItem>(opts);
Debug.Log(optEntry.Content);
OtherItem other = new OtherItem();
SmEntry<OtherItem> othEntry = new SmEntry<OtherItem>(other);
Debug.Log(othEntry.Content);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment