I came across this question in a Microsoft Practice Test and I got confused. Here is the question:     Which of the following C# code samples   is the proper way to raise an event,   assuming that the Alarm event, the   AlarmEventArgs class, and the   AlarmEventHandler delegate have been   declared?   Here is the "correct" answer they provided:  AlarmEventArgs e = new AlarmEventArgs(1, 2); AlarmEventHandler handler = Alarm;  if (handler != null)  {      handler(this, e); }   However, there is also another answer which seems correct.  AlarmEventArgs e = new AlarmEventArgs(1, 2); if (Alarm!= null)  {      Alarm (this, e); }   I personally, always use the second method. It works just fine. Can someone please tell me why I should use the first method instead of second?
31989
Something that confuses me, but has never caused any problems... the recommended way to dispatch an event is as follows:  public event EventHandler SomeEvent; ... {     ....     if(SomeEvent!=null)SomeEvent(); }   In a multi-threaded environment, how does this code guarantee that another thread will not alter the invocation list of SomeEvent between the check for null and the invocation of the event?
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too
26482
Can you explain to me:   What is a Predicate Delegate? Where should we use predicates? Any best practices when using predicates?   Descriptive source code will be appreciated.
12181
Is there a best-practice or common way in JavaScript to have class members as event handlers?  Consider the following simple example:  &lt;head&gt;     &lt;script language="javascript" type="text/javascript"&gt;          ClickCounter = function(buttonId) {             this._clickCount = 0;             document.getElementById(buttonId).onclick = this.buttonClicked;         }          ClickCounter.prototype = {             buttonClicked: function() {                 this._clickCount++;                 alert('the button was clicked ' + this._clickCount + ' times');             }         }      &lt;/script&gt; &lt;/head&gt; &lt;body&gt;     &lt;input type="button" id="btn1" value="Click me" /&gt;     &lt;script language="javascript" type="text/javascript"&gt;         var btn1counter = new ClickCounter('btn1');     &lt;/script&gt; &lt;/body&gt;   The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or this points to some other object.  Any good tips/articles/resources about this kind of problems?
42797
I have a WinForms form that won't close. In OnFormClosing, e.Cancel is set to true. I am guessing that some object in my application has bound to the Closing or FormClosing event, and is blocking the close. To find out, I'd like to determine what delegates are bound to one of these events.  Is there a way to determine the list of handlers bound to an event? Ideally I would do this via the Visual Studio debugger, but can write code in the application to find the handlers if necessary. Understanding that an event is like a hidden private field, I've navigated through the Debugger to the "Non-Public Fields" for the "Windows.Forms.Form" ancestor of my form, but to no avail.
87780
I have a legacy WinForms Mdi App in VB.Net 2.0 which I am adding functionality to. One of the additions is a warning which needs to be raised when the current time nears a specified value (a deadline). My intention is to check the time once an hour until there is less than an hour until the deadline, then display warnings at specified intervals until the time's up.  The user needs to be able to continue to use the app up to and even after the deadline, but they need to periodically be made aware of the deadline's proximity.   The app does not use System.Threading yet and my knowledge of it is limited at this time. I do know that there are 3 different Timer() methods available:    System.Threading.Timer(), Windows.Forms.Timer() and  System.Timers.Timer()   My question is, which is the best way to go with this? I attempted to use the threaded timer, but since WinForms are not thread safe I got a run time error trying to access another class. Is it worth making the class/form thread safe? Am I completely off track?  Thanks.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
45838
If I have the following code:  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass = null;   Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass.MyEvent -= MyFunction; pClass = null;
15516
I have some code that raises PropertyChanged events and I would like to be able to unit test that the events are being raised correctly.  The code that is raising the events is like  public class MyClass : INotifyPropertyChanged {    public event PropertyChangedEventHandler PropertyChanged;       protected void NotifyPropertyChanged(String info)    {         if (PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(info));         }    }       public string MyProperty    {        set        {            if (_myProperty != value)            {                _myProperty = value;                NotifyPropertyChanged("MyProperty");            }        }    } }   I get a nice green test from the following code in my unit tests, that uses delegates:  [TestMethod] public void Test_ThatMyEventIsRaised() {     string actual = null;     MyClass myClass = new MyClass();      myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)     {          actual = e.PropertyName;     };      myClass.MyProperty = "testing";     Assert.IsNotNull(actual);     Assert.AreEqual("MyProperty", actual); }   However, if I then try and chain the setting of properties together like so:  public string MyProperty {     set     {         if (_myProperty != value)         {             _myProperty = value;             NotifyPropertyChanged("MyProperty");             MyOtherProperty = "SomeValue";         }     } }  public string MyOtherProperty {     set     {         if (_myOtherProperty != value)         {             _myOtherProperty = value;             NotifyPropertyChanged("MyOtherProperty");         }     } }   My test for the event fails - the event that it captures is the event for the MyOtherProperty.  I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.  So I'm wondering: 1. Is my method of testing events correct? 2. Is my method of raising chained events correct?
15838
Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:  class GenericClass&lt;T&gt;  {     public event EventHandler&lt;EventData&gt; MyEvent;     public class EventData : EventArgs { /* snip */ }     // ... snip }   Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:  GenericClass&lt;int&gt; gcInt = new GenericClass&lt;int&gt;; gcInt.MyEvent += new EventHandler&lt;GenericClass&lt;int&gt;.EventData&gt;(gcInt_MyEvent); // ...  private void gcInt_MyEvent(object sender, GenericClass&lt;int&gt;.EventData e) {     throw new NotImplementedException(); }   Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...  Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.
97823
I'm updating some old Managed C++ code with lines like this:  instanceOfEventSource-&gt;add_OnMyEvent(      new EventSource::MyEventHandlerDelegate(this, MyEventHandlerMethod) );   where   EventSource is the class that publishes events instanceOfEventSource is an instance of that class EventSource::MyEventHandlerDelegate is the delegate type for the event MyEventHandlerMethod is a (non-static) method within the current class (of which "this" is an instance) with the signature matching EventSource::MyEventHandlerDelegate   What is the right syntax for this in C++/CLI?
3800
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.  Collection was modified; enumeration operation may not execute  Below is the code. This is a WCF server in a Windows service. The method NotifySubscribers() is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day). When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine. Do you see a problem with this code? Do I need to make the dictionary thread-safe? [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class SubscriptionServer : ISubscriptionServer {     private static IDictionary&lt;Guid, Subscriber&gt; subscribers;      public SubscriptionServer()     {                     subscribers = new Dictionary&lt;Guid, Subscriber&gt;();     }      public void NotifySubscribers(DataRecord sr)     {         foreach(Subscriber s in subscribers.Values)         {             try             {                 s.Callback.SignalData(sr);             }             catch (Exception e)             {                 DCS.WriteToApplicationLog(e.Message,                    System.Diagnostics.EventLogEntryType.Error);                  UnsubscribeEvent(s.ClientId);             }         }     }          public Guid SubscribeEvent(string clientDescription)     {         Subscriber subscriber = new Subscriber();         subscriber.Callback = OperationContext.Current.                 GetCallbackChannel&lt;IDCSCallback&gt;();          subscribers.Add(subscriber.ClientId, subscriber);                  return subscriber.ClientId;     }      public void UnsubscribeEvent(Guid clientId)     {         try         {             subscribers.Remove(clientId);         }         catch(Exception e)         {             System.Diagnostics.Debug.WriteLine(&quot;Unsubscribe Error &quot; +                      e.Message);         }     } }
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
2217
The trigger:    What I have been trying for the test class:   I am a total noob when it comes to writing these unit tests. I would greatly appreciate any guidance to help me get this figured out.
2138
Where or when would one would use namespace aliasing like  using someOtherName =  System.Timers.Timer;  It seems to me that it would just add more confusion to understanding the language.
51297
I moved a method that sets addError() from a trigger into a Helper class. As I started writing test code for it it seems like the addError() is not actually preventing DML operations for the records that get modified in the helper class.  The information from the SF  states: Marks a trigger record with a custom error message and prevents any DML operation from occurring.  Does this mean that addError() will not work outside of a trigger class?  EDIT  Adding some sample code.  public class MyHelperClass() {     public static void someMethod(Opportunity opp) {         opp.My_Field__c.addError('Some error');         insert opp;     } }   And sample test for it without any asserts:  @IsTest private class MyHelperClass_Test() {     @IsTest     static void someTest() {         Opportunity opp = new Opportunity();         opp.Name = 'Some Name';         opp.StageName = 'Prospect';         opp.CloseDate = Date.today().addDays(30);          MyHelperClass.someMethod(opp);     } }   The above inserts the opportunity and does not trigger an exception. Am I doing something wrong?