C#TheLanguage Flashcards
What is a delegate in C#? How is a delegate declared, instantiated, used?
A C# delegate is a type that represents a reference to .a method with a particular parameter list and return types. When instantiating a delegate you associate it to a particular method, and then you can invoke that method through the delegate.
// Declare a delegate public delegate int PerformCalc(int x, int y); This is a delegate that can point to a method which takes 2 ints and returns an int.
// Method to be encapsulated in delegate public int AddMethod(int a, int b) { return a + b; }
// Instantiate the delegate PerformCalc calcHandler = new PerformCalc(AddMethod); // Or PerformCalc calcHandler = AddMethod;
// Call the delegate calcHandler(1, 4) // returns 5
A delegate can have more than one method in its invocation list:
calcHandler += AnotherCalcMethod
Calling the delegate calls each of the methods in the order in which they were added. If there is a return value, it will be the value returned by the last method.
Delegates allow for things like passing methods as parameters, having callback methods etc.
What is a Func?
A predefined delegate which takes optional parameters and returns a value.
// declare func which takes 2 ints and returns a string Func myFunc; // the last type parameter is the return type (string in this case) instantiate e.g. with lambda myFunc = (num1, num2) => { return "hello world" }
What is an Action?
A built-in delegate that takes optional parameters and does not return a value.
// declare Action myAction; // the method to assign public void doStuff(int a, string b) { // do stuff } // instantiate action myAction = doStuff; // call myAction(5, "hello world");
// with anonymous method myAction = delegate(int c, string d) { // do stuff }
// with lambda myAction = (num, word) => { //do stuff }
What is a Predicate?
A predefined delegate that takes one parameter T and returns a bool // predicate which takes a person object and returns true if name is Claire Predicate myPredicate = (p) => { return p.Name == "Claire" } // Then can pass to Linq I think? List people = new List(); //... people.Where(myPredicate); // returns list of people matching the predicate // this is the equivalent of doing this: people.Where(p => p.Name == "Claire");
What is a c# event and how does it relate to delegates?
An Event declaration adds a layer of abstraction and protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.
To have and raise an event you need 3 things:
- A delegate definition
- An event definition
- A method called to raise the event (call the event/delegate)
delegate definition:
public delegate int WorkPerformedHandler(int hours);
event definition (with the delegate type defined above): public event WorkPerformedHandler WorkPerformed;
method: protected virtual void OnWorkPerformed(int hours) { // Check event/delegate is not null // that means it has been subscribed to if(WorkPerformed != null) { WorkPerformed(hours); // this calls the delegate, e.g. calls the methods that have subscribed to the event i.e the methods that the delegate is referencing! } }
// Declare // General form: public event {Delegate type} {event name} // Example: public event EventHandler Punch; // Can also use generic event handler public event EventHandler Punch // EventHandler is a built in delegate type // can also use custom delegate public event MyCustomEventHandler Punch;
// Method where you raise the event (good idea to make // virtual so can be overridden public virtual void OnPunch() { // Either use event directly, OR //get the delegate from the event e.g. MyDelegate handler = Punch as MyDelegate; // check if not null, meaning there are subscribers if(handler != null) { // raise event handler(this, EventArgs.Empty) // or whatever parameters accepted by the delegate } }
Subscribing to event (in other class): classWithEvent = new ClassWithEvent() classWithEvent.Punch += MyMethod
public void MyMethod(object source, EventArgs args) { // react to event }
// Or with anonymous method classWithEvent.Punch += delegate(object source, EventArgs args) { // body }
// Or with lambda classWithEvent.Punch += (source, args) => {// body}
What is a lambda
As far as I understand it is syntactic sugar/concise notation for a delegate. Wherever I use a lambda it is expecting a function/action with a specific signature (return type and parameters), which is how it infers the types of the lambda parameters. So if I do something like list.Where(x => x.id == 1), that Where method is expecting a delegate (i.e. function or action) which takes whatever type x is as a parameter and returns true if it meets condition
Questions on asynchronous programming
https://docs.microsoft.com/en-us/dotnet/csharp/async
AND do pluralsight course!
AND WATCH THIS VIDEO https://www.youtube.com/watch?v=0qiB3oW_nd8
Expressions and expression trees
todo
C# Closures?
todo
What are generics and why use them? How can you constrain generics? How are C# generics different from Java Generics?
todo
What is the async keyword?
The async keyword is used to indicate that a method can contain the await keyword.
What is the await keyword?
The await keyword is used to interrupt the flow of the code until the Task being awaited has completed. It releases the thread it is running on, and when the task completes execution is returned to that point in the code.
What is a Task?
A Task represents a concurrent operation. It’s an abstraction, a wrapper around a concurrent operation. IT may or may not run on a separate thread.
You can do things with it like ContinueWith(code to run after it’s complete), check it’s status etc.
What is configureawait?
todo
Wait, await, configureawait and deadlocking, what gives?
todo