0

I have not been able to figure out the purpose of the "new()" word in this code. I appreciate any insight and help understanding it. What is the meaning/functionality of "new()" in this piece of code?

 public abstract class GameManagerBase<TGameManager, TDataStore> : PersistentSingleton<TGameManager>
    where TDataStore : GameDataStoreBase, new()
    where TGameManager : GameManagerBase<TGameManager, TDataStore>

 public abstract class GameDataStoreBase : IDataStore
{
    public float masterVolume = 1;

    public float sfxVolume = 1;

    public float musicVolume = 1;

    /// <summary>
    /// Called just before we save
    /// </summary>
    public abstract void PreSave();

    /// <summary>
    /// Called just after load
    /// </summary>
    public abstract void PostLoad();
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
luis
  • 107
  • 1
  • 8
  • It's a generic type constraint: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint – UnholySheep Dec 08 '21 at 16:32

1 Answers1

1

This is actually not Unity3d specific but general c#.

In this case where is a type constraint for the generic type parameter TDataStore. Meaning when you actually implement

public class Example : GameManagerBase<SomeManager, SomeStore> { ... }

the type SomeStore has to fulfill whatever constraints are given for the TDataStore - which can be a certain base class, interfaces and some special constraints.


The new() is such a special constraint.

It means that TDataStore has to be a type that provides a public parameter-less constructor. This is required for being able to create instances of the given type (without using ugly Reflection).

derHugo
  • 83,094
  • 9
  • 75
  • 115