Hello,
I’m looking through someone else’s code base on a small project, something I’ve not really done before to any extent. There’s a few things in the code base I’m not used to seeing, and one such thing is copious use of “this”, including in places where I know it isn’t strictly necessary. However, one place they use “this” is in the parameters of functions in a public static class called “Extensions”, e.g:
public static Vector3 ToVector3(this Vector3Int vector) {
return (Vector3)(vector);
}
public static T PickRandom<T>(this ICollection<T> collection) {
int index = UnityEngine.Random.Range(0, collection.Count);
return collection.ElementAt(index);
}
public static T GetBest<T>(this IEnumerable<T> enumerable, Func<T, float> property) {
float bestValue = float.NegativeInfinity;
T bestItem = default(T);
foreach (var item in enumerable) {
float value = property.Invoke(item);
if (value > bestValue) {
bestValue = value;
bestItem = item;
}
}
return bestItem;
}
Is there any reason to use “this” in front of the first parameter like in the code above?
To give a random example of how else they’re using “this”, here’s the top of one of their scripts:
public class InfiniteMap : AbstractMap {
private Dictionary<Vector3Int, Slot> slots;
public readonly int Height;
public Vector3Int rangeLimitCenter;
public int RangeLimit = 80;
private TilingMap defaultColumn;
public InfiniteMap(int height) : base() {
this.Height = height;
this.slots = new Dictionary<Vector3Int, Slot>();
this.defaultColumn = new TilingMap(new Vector3Int(1, height, 1));
if (ModuleData.Current == null || ModuleData.Current.Length == 0) {
throw new InvalidOperationException("Module data was not available, please create module data first.");
}
}
As far as I can see, “this” is entirely superfluous in the “InfiniteMap” function, but I’m also not sure about why this function has the " : base()" on the end (I think it’s just calling the constructor for the base class, but I’m not sure).