Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / July 2006

Tip: Looking for answers? Try searching our database.

Events in C#

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
pSm - 19 Jul 2006 06:21 GMT
When I override the 'add' and 'remove' methods for an event, why can't I
invoke it ? The sample code is provided below - I have two events - 'my' and
'ev' - while invoking, my() works but ev() does not ! The compiler complains
that : The event "'Blog.EventsvsDelegates.Form1.ev' can only appear on the
left hand side of += or -="

Why ?  

       public delegate void MyEvent();
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button button1;
        private event MyEvent my;

        private event MyEvent pvt_ev;
        public event MyEvent ev
        {
            add
            {
                    pvt_ev +=value;
            }

            remove
            {
                pvt_ev-=value;
            }
        }
                     
        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            my+=new MyEvent(this.Test);
            my+=new MyEvent(this.Test1);

            ev+=new MyEvent (this.Test );
        }

        protected void Test()
        {
            MessageBox.Show ("Test");
        }

        protected void Test1()
        {
            MessageBox.Show ("Test1");
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
             my(); // WORKS
                     //ev (); //DOES NOT WORK
        }

    }
Larry Lard - 19 Jul 2006 10:12 GMT
> When I override the 'add' and 'remove' methods for an event, why can't I
> invoke it ? The sample code is provided below - I have two events - 'my' and
[quoted text clipped - 3 lines]
>
> Why ?  

The help page for this error (CS0079) includes a sample very similar to
yours that shows you exactly what to do. I found this out by reproducing
your sample then hitting F1 with the error selected...

Signature

Larry Lard
larrylard@googlemail.com
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version

pSm - 19 Jul 2006 13:39 GMT
Thanks Larry.

But this does not really answer my question ! Why does the compiler restrict
the invocation ?
Jon Skeet [C# MVP] - 19 Jul 2006 17:34 GMT
> When I override the 'add' and 'remove' methods for an event, why can't I
> invoke it ? The sample code is provided below - I have two events - 'my' and
> 'ev' - while invoking, my() works but ev() does not ! The compiler complains
> that : The event "'Blog.EventsvsDelegates.Form1.ev' can only appear on the
> left hand side of += or -="

And it's right. An event is really just an add/remove pair of methods.
(There's also raise, but that doesn't get exposed in C#.) When you
declare a field-like event, that's really declaring both the event
*and* a delegate. When you access the name within the class, it refers
to the delegate. When you access the name outside the class, it refers
to the event. Delegates can be invoked - events can't.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Lloyd Dupont - 20 Jul 2006 01:25 GMT
> And it's right. An event is really just an add/remove pair of methods.
> (There's also raise, but that doesn't get exposed in C#.) When you

No, there is no such thing as "raise"!
Events are stored as multicast delegates and used as such.

> declare a field-like event, that's really declaring both the event
> *and* a delegate. When you access the name within the class, it refers
> to the delegate. When you access the name outside the class, it refers
> to the event. Delegates can be invoked - events can't.

Well events are just delegate, and of course they could be ".Invoke(..)", as
any other delegate.
But a semantic akin to private/protect/public prevent to do it from anywhere
but the declaring class itself.
Jon Skeet [C# MVP] - 20 Jul 2006 08:03 GMT
> > And it's right. An event is really just an add/remove pair of methods.
> > (There's also raise, but that doesn't get exposed in C#.) When you
>
> No, there is no such thing as "raise"!
> Events are stored as multicast delegates and used as such.

C# doesn't expose it, but it's part of the .NET event system.
See CLI spec partition 1 section 10.4.

> > declare a field-like event, that's really declaring both the event
> > *and* a delegate. When you access the name within the class, it refers
[quoted text clipped - 3 lines]
> Well events are just delegate, and of course they could be ".Invoke(..)", as
> any other delegate.

No, events aren't delegates any more than properties are variables. An
event is solely a set of appropriately decorated methods. It's possible
(although it would be very odd) to implement an event without actually
storing a delegate. You'd need to store pretty much the same
information, but the only ways in which events are intrinsically linked
to delegates are:

1) C#'s field-like event support, which declares a delegate variable
and an event
2) the signatures of event methods.

> But a semantic akin to private/protect/public prevent to do it from anywhere
> but the declaring class itself.

Events only have add/remove semantics, along with the raise as
mentioned before. Whether they are implemented by having a delegate
variable is an implementation matter. Some implementations keep the
delegates for all events in a hashtable, so that you don't need a
variable per event where there are lots of events which may not be
subscribed to at all.

Jon
Lloyd Dupont - 20 Jul 2006 02:26 GMT
give pvt_ev a public accessor.
otherwise it's quite obvious, if you have no access to it, how could you
hope invoke it?!?!

> When I override the 'add' and 'remove' methods for an event, why can't I
> invoke it ? The sample code is provided below - I have two events - 'my'
[quoted text clipped - 65 lines]
>
> }
pSm - 20 Jul 2006 04:55 GMT
Lloyd,
  Why would pvt_ev() need a public accessor when I invoke it from the same
class ? In fact any 'event' that is declared as public, would be converted to
'private' by the compiler - events can never be invoked from outside it's
class.
   
I was checking the MSIL and noticed that when 'add' and 'remove' accessors
are declared, the ev declaration is removed, and so invoke on ev() no longer
works.

I had posted this question on GOTDOTNET discussion forum too and I think
Alan came close to answering why the compiler does not allow invoking ev().

You can read the whole story here : <a
href="http://blogs.ittoolbox.com/visualbasic/operating/archives/events-vs-delegates-co
ntd-10596">Events
vs Delegates </a>

> give pvt_ev a public accessor.
> otherwise it's quite obvious, if you have no access to it, how could you
[quoted text clipped - 69 lines]
> >
> > }
Lloyd Dupont - 20 Jul 2006 08:50 GMT
>   Why would pvt_ev() need a public accessor when I invoke it from the same
> class ?
Sorry, I misread your sample.
just change:
>> > private void button1_Click(object sender, System.EventArgs e)
>> > {
>> >                   //ev (); //DOES NOT WORK
>> > }
to
private void button1_Click(object sender, System.EventArgs e)
{
                  pvt_ev ();
}

> In fact any 'event' that is declared as public, would be converted to
> 'private' by the compiler - events can never be invoked from outside it's
[quoted text clipped - 89 lines]
>> >
>> > }
Lloyd Dupont - 20 Jul 2006 08:52 GMT
Oops,
I think I misread you anyway.
It was more of a phylosophical debate rather than a practical question.
Dimiss my previous answer....

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.