Jump to content

Why doesn't this work in C#?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
AtoZ

AtoZ

    Learning Programmer

  • Members
  • PipPipPip
  • 36 posts
using System;

using System.Diagnostics;

using System.Speech.Recognition;


    class program

    {


        SpeechRecognizer rec = new SpeechRecognizer();


        public static void Main()

        {

            rec.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(rec_SpeechRecognized);

        }


        private void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)

        {

         

        }

        

    }

It acts like rec is not in scope but surely it is?

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Not work as in "gives errors" (which ones?) or not work as "i've put a breakpoint at the rec_SpeechRecognized(..) and noticed it doesn't go there"?

1 or 2 possible things could most likely go wrong:

1) The System.Speech library isn't properly added. To fix this do the following:

  • Go to the solution explorer. look for "References" right click it and choose "Add Reference..."
    Posted Image


  • A new window pops up (maybe has to load a while). Search the list for "System.Speech", select it and click "Ok"
    Posted Image

    Now it's properly added and ready to use.


2) This one is certainly wrong: You access "rec" from inside the main method. Problem is, the main method is "Static" and the rec variable is not. This means that Main can be called when there doesn't has to be a 'program'-object. But rec only exists when there is a 'program'-object. Also all program-objects share the same static methods/attributes/variables. So when there would be 2 objects, the Main method would have no idea which "rec" to take.

Solution
  • Place the rec.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(rec_SpeechRecognized); line in the constructor of "program"
  • Create a new "program" object in the Main (program prog = new program() )



And finally, your class should/must begin with a capital letter.
See .NET Naming Conventions




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users