-1

I want to understand the use of "protected" keyword in the following code (line 3).

  public class  PlayerData
  {
     static protected PlayerData instance;
     static public PlayerData Instance { get { return instance; } }

     public int health;
  }


  public class GameManager
  {
      PlayerData.Instance.health = 10;
  }
Achie1
  • 195
  • 2
  • 13
  • 3
    Do you know what `protected` means? – Good Night Nerd Pride Jun 12 '21 at 15:37
  • 1
    A derived class could replace the instance completely, because it's protected. But that's bad design. Most design guidelines suggest that member variables (whether static or not) should always be private. – PMF Jun 12 '21 at 15:38
  • 2
    i suggest asking the author. they oughta know why they did what they did. – Franz Gleichmann Jun 12 '21 at 15:43
  • Yes I know what protected means : A protected member is accessible within its class and by derived class instances. I ask this question because there is no inheritance here. So I thought he wrote this code for a specific reason. I just want to learn – Achie1 Jun 12 '21 at 15:50
  • 1
    It has been written by Unity 3D developers. I found it in the game named Trash Dash. The name of the script is PlayerData. – Achie1 Jun 12 '21 at 15:58

1 Answers1

2

A private field is not accessible from a child class.

A protected field can be.

If the field is protected, we can inherit from this class and use this field instead of the property.

This avoids the use of the getter which is a method, and that is a crazy time consuming via a CPU PROC CALL and RET using the CPU STACK to return the reference.

Thus it is more speed optimized to use the field instance instead of teh property Instance because we directly use the reference without the need of a method call that will slow down the process and the current thread, thus the game.

Approximately ~5x faster, way to speak vaguely, for each usage.

But that said, we must be carefull to not change the underlying object instance, unless we have a good reason. This field could be read-only, but it is not, who knows why. Perhaps to be able to change the object... either it is just an oversight, or this ref is assigned outside a constructor, or can be reassigner at any time.

  • Property getters and setters will almost always be inlined by the compiler or JIT optimization. Hence, your claimed 5x speed advantage is speculative to say the least. – Good Night Nerd Pride Jun 12 '21 at 16:31
  • @GoodNightNerdPride Indeed, what I said it theoric. I have no particular knowledge of what you mention. But we cannot rely on possible optimization at such a low-level as this is not guaranteed since .NET IL code is not inlined like C inline functions are. And that, depends on many things that can vary from one platform to another, and from one implementation to another. –  Jun 12 '21 at 16:34