H6 Delegates, Events, Exceptions Flashcards
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.
How do you create a catch section that captures all exception types?
ommit the exception type:
int quantity; try { quantity = int.Parse(quantityTextBox.Text); } catch { MessageBox.Show("The quantity must be an integer."); }
How do you create a catch section that captures all exception types?
ommit the exception type:
int quantity; try { quantity = int.Parse(quantityTextBox.Text); } catch { MessageBox.Show("The quantity must be an integer."); }
Is this allowed :
try{…}
catch(IOException)
{…}
So no variable after the exception type.
Yes:
If you include the ExceptionType but omit variable, then the catch section executes for matching
exception types, but the code doesn’t have a variable that can give information about the exception.
what is the eqevilant behavoir between a using statement and try/finaly block?
The Despose() methode will always be called no matter how the using section is left e.g. return, throw an exception in the using statement ect…
Which methodes can you use the check for an overflow of a float?
IsInfinity
Returns true if the value is PositiveInfinity or NegativeInfinity
IsNaN
Returns true if the value is NaN
IsNegativeInfinity
Returns true if the value is NegativeInfinity
IsPositiveInfinity
Returns true if the value is PositiveInfinity
What are the Exception class properties?
Data: A collection of key/value pairs that give extra information about the exception.
HelpLink: A link to a help file associated with the exception.
HResult: A numeric code describing the exception.
InnerException: An Exception object that gives more information about the exception. Some
libraries catch exceptions and wrap them in new exception objects to provide information that is more relevant to the library. In that case, they may include a
reference to the original exception in the InnerException property.
Message: A message describing the exception in general terms.
Source: The name of the application or object that caused the exception.
StackTrace: A string representation of the program’s stack trace when the exception occurred.
TargetSite: Information about the method that threw the exception.
How do you get more specfic info from an exception class for debugging?
User toString()
System.OverflowException: Arithmetic operation resulted in an overflow.
at OrderProcessor.OrderForm.CalculateSubtotal() in
d:\Support\Apps\OrderProcessor\OrderForm.cs:line 166
returns: Exception class/Methode that caused it/file
Which exception can a checked{…} block throw?
OverflowException
What is the difference when retrowing an exception between “throw” and “throw ex”?
First one throws the origional exception and leaves the stacktrace in tact, second one resets the stacktrace to the point where the exception was rethrown.
How can you take the exception data to e.g. write to a log file but in the same time do not change the stacktrace?
try { // Do something dangerous. ... } catch (Exception) { // Log the error. ... // Re-throw the exception. throw; //Note : there is no exception reference used, only throw. }
What is a good design pattern when creating your own exception class?
Inherit from the excption class. Create the same constructors as the Excption class has and use base(...) to call that constructor.
What debug methode can you use to throw an exception when checking data?
Debug.Assert(items.Length an exception is thrown.
This only happens in debug mode.
In release mode this is ingnored.