-2

I can't undersdand, why mustn't I instantiate the delegates out the method Run in code bellow?

public class Tester
{
    Media myMedia = new Media();
    AudioFile myAu = new AudioFile();
    VideoFile myVd = new VideoFile();
    //instantiate the delegates
    Media.PlayerD MyDA = new Media.PlayerD(myAu.AudioPlay);
    Media.PlayerD MyDV = new Media.PlayerD(myVd.VideoPlay);

    public void Run()
    {
        //call the delegates
        myMedia.Report(MyDA);
        myMedia.Report(MyDV);
    }
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • I am sorry, but I can't get what you are asking. Could you please rephrase your question? You don't understand why you instantiate the delegates on the class level and you assign them to two fields of the class? You don't understand why another approach is followed - like instatiating them inside the body of the method called `Run`? Thanks – Christos Feb 25 '17 at 16:20
  • What is the type `Media` used for `myMedia`? And is `PlayerD` a delegate type that is nested inside the `Media` type? Please show their definitions (or provide a link to their documentation). – Jeppe Stig Nielsen Feb 25 '17 at 17:03
  • Unfortanly, forum couldn't to write all code. This is example of book. Pass two method through the delegate and invoke it through the method Run() in class Tester. Why I can't instantiate the delegates out the method Run()? – Valerii Kozhevnikov Feb 26 '17 at 15:52

1 Answers1

0

You:

Media.PlayerD MyDA = new Media.PlayerD(myAu.AudioPlay);

An initializer of a non-static field (MyDA above) cannot use another non-static field (myAu).

It would be permitted if you put MyDA = new Media.PlayerD(myAu.AudioPlay); inside a non-static constructor instead.

(The same for MyDV, of course.)

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • Why can't use? Why I must instantiate the delegates inside the method? – Valerii Kozhevnikov Feb 26 '17 at 15:46
  • That is simply per design of C#. The people who designed C# decided that if non-static data on the class depends on other non-static data, you must set up things in a constructor where the initialization order and algorithm is explicit. See other threads like [A field initializer cannot reference the nonstatic field, method, or property](http://stackoverflow.com/questions/14439231/) (the error message you get). __But what are you trying to achieve?__ You can also create a `get`-only property with `Media.PlayerD MyDA => myAu.AudioPlay;`. It will return a new instance each time, however. – Jeppe Stig Nielsen Feb 26 '17 at 20:42