H6 Delegates, Events, Exceptions Flashcards
(36 cards)
What is a delegate, give an example.
A delegate is a type.
example : [accessibility] delegate returnType DelegateName([parameters]);
private delegate float FunctionDelegate(float x);
What naming convention is used with delegates and callbacks?
Function(Delegate) or InvoiceGenerated(Callback).
The callback uses a delegate to address the target methode.
Give an example of a list of delegates.
List functions = new List();
Give an example of Addition and subtraction of delegates.
Action del1 = Method1;
Action del2 = Method2;
Action del3 = del1 + del2 + del1;
This makes del3 a delegate variable that includes a series of other delegate variables. Now if you invoke the del3 delegate variable, the program executes Method1 followed by Method2 followed by Method1.
You can even use subtraction to remove one of the delegates from the series. For example, if you execute
the statement del3 -= del1 and then invoke del3, the program executes Method1 and then Method2.
what is : Covariance
Covariance lets a method return a value from a subclass of the result expected by a delegate. For example, suppose the Employee class is derived from the Person class and the ReturnPersonDelegate type represents methods that return a Person object. Then you could set a ReturnPersonDelegate variable equal to a method that returns an Employee because Employee is a subclass of Person. This makes sense because the method should return a Person, and an Employee is a kind of Person. (A variable is called covariant if it enables covariance.)
what is : Contravariance
Contravariance lets a method take parameters that are from a superclass of the type expected by a delegate. For example, suppose the EmployeeParameterDelegate type represents methods that take an Employee object as a parameter. Then you could set an EmployeeParameterDelegate variable equal to a method that takes a Person as a parameter because Person is a superclass of Employee. When you invoke the delegate variable’s method, you will pass it an Employee (because the delegate requires that the method take an Employee parameter) and an Employee is a kind of Person, so the method can handle it. (A variable is called contravariant if it enables contravariance.)
what is a Action Delegate give an example.
The generic Action delegate represents a method that returns void.
public delegate void Action(T1 arg1, T2 arg2)
// Method 1. private delegate void EmployeeParameterDelegate(Employee employee); private EmployeeParameterDelegate EmployeeParameterMethod1;
// Method 2. private Action{Employee} ParameterMethod2;
what is a Func Delegate give an example.
he generic Func delegate represents a method that returns a value.
public delegate TResult Func{in T1, in T2, out TResult}(T1 arg1, T2 arg2)
// Method 1. private delegate Person ReturnPersonDelegate(); private ReturnPersonDelegate ReturnPersonMethod1;
// Method 2. private Func{Person} ReturnPersonMethod2;
What is a Anonymous Methods in relation to a delegate, give an example.
delegate([parameters]) { code… }
The following code stores an anonymous method in a variable of a delegate type.
private Func Function = delegate(float x) { return x * x; };
private void Form1_Load(object sender, EventArgs e)
{
this.Paint += delegate(object obj, PaintEventArgs args)
{
args.Graphics.DrawEllipse(Pens.Red, 10, 10, 200, 100);
};
}
private void Form1_Load(object sender, EventArgs e)
{
System.Threading.Thread thread = new System.Threading.Thread(
delegate() { MessageBox.Show(“Hello World”); }
);
thread.Start();
}
What is a lambda expression and give an example.
() => expression;
Action note;
note = () => MessageBox.Show(“Hi”);
note();
same code a bit shorter:
Action note = () => MessageBox.Show(“Hi”);
How does the compiler know that the parameter is of type string?
Action{string} note = (message) => MessageBox.Show(message);
Is is defined in the Action{string}
What can you leave out with a lambda expression if there is only 1 parameter?
You can leave out the opening and closing bracets for the parameter, e.g in this case the parameter “message”
Action note = message => MessageBox.Show(message);
Can you explicitly define parameter types using lambda?
Yes:
Action note = (string message) => MessageBox.Show(message);
Give an example of a lambda expression that has 4 parameters?
Action{string, string, MessageBoxButtons, MessageBoxIcon} note;
note = (message, caption, buttons, icon) =>
MessageBox.Show(message, caption, buttons, icon);
note(“Invalid input”, “Alert”, MessageBoxButtons.OK,
MessageBoxIcon.Asterisk);
Give an example using Func for a lambda expression that returns a value.
Func{float, float} square = (float x) => x * x;
float y = square(13);
What is the difference between Statement Lambdas and expresion lambdas?
Expression lambdas do not have a return keyword and are one liners, they do not use {..}
An exampe is : TheFunction = x => (float)(12 * Math.Sin(3 * x) / (1 + Math.Abs(x)));
Statement Lambdas :
Use {…} can hold multiple lines of code and you need to use the return keyword.
How can you make a lambda Async?
Put the async keyword infront of it:
// The number of times we have run DoSomethingAsync. private int Trials = 0; // Create an event handler for the button. private void Form1_Load(object sender, EventArgs e) { runAsyncButton.Click += async (button, buttonArgs) => { int trial = ++Trials; statusLabel.Text = "Running trial " + trial.ToString() + "..."; await DoSomethingAsync(); statusLabel.Text = "Done with trial " + trial.ToString(); }; } // Do something time consuming. async Task DoSomethingAsync() { // In this example, just waste some time. await Task.Delay(3000); }
Give an example of an event definition.
accessibility event delegate EventName;
Here’s a breakdown of that code:
accessibility : The event’s accessibility as in public or private.
event: The event keyword.
delegate: A delegate type that defines the kind of method that can act as an event handler
for the event.
EventName : The name that the class is giving the event.
public delegate void OverdrawnEventHandler();
public event OverdrawnEventHandler Overdrawn;
What default event handler delegate can you use when you only need to define the eventArgObject?
public event EventHandler{MyEventArgClassInstance} Overdrawn(=Eventname);
EventHandler here is the predefined delegate type like action/func
Can delegates also be used in stuct?
Yes
How can you filter exceptions?
try { Statements... } catch (SystemException ex) { Statements... } catch (FormatException ex) { Statements... } catch (Exception ex) { Statements... }
Which exception type is higher in the hierarchy?
Exception -> SystemException -> FormatException
What is equal to catch(Exception ex)?
Omit the (Exception ex) equals catch(Exception ex):
try { quantity = int.Parse(quantityTextBox.Text); } catch { MessageBox.Show("The quantity must be an integer."); }
The Finaly methode when that does get executed?
Always, event if the try methodes does a return.