2

I get the "Field 'UIHandler.handlerNewPlayer' is never used..." notification on this code:

class UIHandlerMain : IUIHandlerMain
    {
        public UIHandlerMain()
        {
            IUIHandlerNewPlayer handlerNewPlayer = new UIHandlerNewPlayer();
        }

        public IUIHandlerNewPlayer HandlerNewPlayer { get; }
    }

I am new to C#, but it seems to me the the auto-implemented handlerNewPlayer is being set up in the Constructor. Obviously, I am missing something simple and fundamental.

SmileyFtW
  • 326
  • 2
  • 10
  • Your example does not include a field named `handlerNewPlayer`. – John Wu Dec 17 '19 at 22:38
  • My understanding is that the HandlerNewPlayer getter auto-implements the backing field handlerNewPlayer. – SmileyFtW Dec 18 '19 at 18:59
  • 1
    That understanding is incorrect. See [Is it possible to access backing fields behind auto-implemented properties?](https://stackoverflow.com/questions/8817070/is-it-possible-to-access-backing-fields-behind-auto-implemented-properties). It is best to access the property via its property and not attempt to access the backing field yourself--- its naming prevents that (by design) unless you do something weird, like use Reflection. – John Wu Dec 18 '19 at 19:31
  • @JohnWu - thank you! I will go through the property. If you'l do your answer in an "Answer" I'll mark it as answered. – SmileyFtW Dec 18 '19 at 19:49

1 Answers1

5

In your constructor, you are declaring a local variable named handlerNewPlayer - the property HandlerNewPlayer is never assigned to. For that, you'd have to write something like:

public UIHandlerMain()
{
    HandlerNewPlayer = new UIHandlerNewPlayer();
}
germi
  • 4,628
  • 1
  • 21
  • 38