Creating custom EventArgs containing C# with Example



Creating custom EventArgs containing C# with Example

additional data 
Custom events usually need custom event arguments containing information about the event. For example 
MouseEventArgs which is used by mouse events like MouseDown or MouseUp events, contains information about 
Location or Buttons which used to generate the event. 
When creating new events, to create a custom event arg: 
Create a class deriving from EventArgs and define properties for necessary data. 
As a convention, the name of the class should ends with EventArgs. 
Example 
In the below example, we create a PriceChangingEventArgs event for Price property of a class. The event data 
class contains a CurrentPrice and a NewPrice. The event raises when you assign a new value to Price property and 
lets the consumer know the value is changing and let them to know about current price and new price: 
PriceChangingEventArgs 
public class PriceChangingEventArgs : EventArgs 
{ 
public PriceChangingEventArgs(int currentPrice, int newPrice) 
{ 
this.CurrentPrice = currentPrice; 
this.NewPrice = newPrice; 
} 
public int CurrentPrice { get; private set; } 
public int NewPrice { get; private set; } 
} 
Product 
public class Product 
{ 
public event EventHandler PriceChanging; 
int price; 
public int Price 
{ 
get { return price; } 
set 
{ 
var e = new PriceChangingEventArgs(price, value); 
OnPriceChanging(e); 
price = value; 
} 
} 
protected void OnPriceChanging(PriceChangingEventArgs e) 
{ 
var handler = PriceChanging; 
if (handler != null) 
handler(this, e); 
} 
 

} 
You can enhance the example by allowing the consumer to change the new value and then the value will be used 
for property. To do so it's enough to apply these changes in classes. 
Change the definition of NewPrice to be settable: 
public int NewPrice { get; set; } 
Change the definition of Price to use e.NewPrice as value of property, after calling OnPriceChanging : 
int price; 
public int Price 
{ 
get { return price; } 
set 
{ 
var e = new PriceChangingEventArgs(price, value); 
OnPriceChanging(e); 
price = e.NewPrice; 
} 
} 
 

Parameter Details 
TDelegate The delegate type to be used for the expression 
lambdaExpression The lambda expression (ex. num => num < 5) 
Expression Trees are Expressions arranged in a treelike data structure. Each node in the tree is a representation of 
an expression, an expression being code. An In-Memory representation of a Lambda expression would be an 
Expression tree, which holds the actual elements (i.e. code) of the query, but not its result. Expression trees make 
the structure of a lambda expression transparent and explicit. 

0 Comment's

Comment Form

Submit Comment