H6 Delegates, Events, Exceptions Flashcards

1
Q

What is a delegate, give an example.

A

A delegate is a type.
example : [accessibility] delegate returnType DelegateName([parameters]);

private delegate float FunctionDelegate(float x);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What naming convention is used with delegates and callbacks?

A

Function(Delegate) or InvoiceGenerated(Callback).

The callback uses a delegate to address the target methode.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give an example of a list of delegates.

A

List functions = new List();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give an example of Addition and subtraction of delegates.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is : Covariance

A
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.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what is : Contravariance

A
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.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is a Action Delegate give an example.

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what is a Func Delegate give an example.

A

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;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a Anonymous Methods in relation to a delegate, give an example.

A

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();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a lambda expression and give an example.

A

() => expression;

Action note;
note = () => MessageBox.Show(“Hi”);
note();

same code a bit shorter:

Action note = () => MessageBox.Show(“Hi”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How does the compiler know that the parameter is of type string?

Action{string} note = (message) => MessageBox.Show(message);

A

Is is defined in the Action{string}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What can you leave out with a lambda expression if there is only 1 parameter?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Can you explicitly define parameter types using lambda?

A

Yes:

Action note = (string message) => MessageBox.Show(message);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Give an example of a lambda expression that has 4 parameters?

A

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);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Give an example using Func for a lambda expression that returns a value.

A

Func{float, float} square = (float x) => x * x;

float y = square(13);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between Statement Lambdas and expresion lambdas?

A

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.

17
Q

How can you make a lambda Async?

A

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);
}
18
Q

Give an example of an event definition.

A

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;

19
Q

What default event handler delegate can you use when you only need to define the eventArgObject?

A

public event EventHandler{MyEventArgClassInstance} Overdrawn(=Eventname);

EventHandler here is the predefined delegate type like action/func

20
Q

Can delegates also be used in stuct?

A

Yes

21
Q

How can you filter exceptions?

A
try
{
Statements...
}
catch (SystemException ex)
{
Statements...
}
catch (FormatException ex)
{
Statements...
}
catch (Exception ex)
{
Statements...
}
22
Q

Which exception type is higher in the hierarchy?

A

Exception -> SystemException -> FormatException

23
Q

What is equal to catch(Exception ex)?

A

Omit the (Exception ex) equals catch(Exception ex):

try
{
quantity = int.Parse(quantityTextBox.Text);
}
catch
{
MessageBox.Show("The quantity must be an integer.");
}
24
Q

The Finaly methode when that does get executed?

A

Always, event if the try methodes does a return.

25
Q

How do you create a catch section that captures all exception types?

A

ommit the exception type:

int quantity;
try
{
quantity = int.Parse(quantityTextBox.Text);
}
catch
{
MessageBox.Show("The quantity must be an integer.");
}
26
Q

How do you create a catch section that captures all exception types?

A

ommit the exception type:

int quantity;
try
{
quantity = int.Parse(quantityTextBox.Text);
}
catch
{
MessageBox.Show("The quantity must be an integer.");
}
27
Q

Is this allowed :

try{…}
catch(IOException)
{…}

So no variable after the exception type.

A

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.

28
Q

what is the eqevilant behavoir between a using statement and try/finaly block?

A

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…

29
Q

Which methodes can you use the check for an overflow of a float?

A

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

30
Q

What are the Exception class properties?

A

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.

31
Q

How do you get more specfic info from an exception class for debugging?

A

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

32
Q

Which exception can a checked{…} block throw?

A

OverflowException

33
Q

What is the difference when retrowing an exception between “throw” and “throw ex”?

A

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.

34
Q

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?

A
try
{
// Do something dangerous.
...
}
catch (Exception)
{
// Log the error.
...
// Re-throw the exception.
throw; //Note : there is no exception reference used, only throw.
}
35
Q

What is a good design pattern when creating your own exception class?

A
Inherit from the excption class.
Create the same constructors as the Excption class has and use base(...) to call that constructor.
36
Q

What debug methode can you use to throw an exception when checking data?

A

Debug.Assert(items.Length an exception is thrown.

This only happens in debug mode.
In release mode this is ingnored.