.NET Core and C#

Lab 5

Again some quick knowledge refresher

Named Arguments

class NamedExample
{
    static void Main(string[] args)
    {
        // The usual way
        PrintOrderDetails("Gift Shop", 31, "Red Mug");

        // Named arguments can be supplied for the parameters in any order.
        PrintOrderDetails(orderNum: 31, productName: "Red Mug", sellerName: "Gift Shop");

        // Named arguments mixed with positional arguments are valid
        // as long as they are used in their correct position.
        PrintOrderDetails("Gift Shop", 31, productName: "Red Mug");
        PrintOrderDetails(sellerName: "Gift Shop", 31, productName: "Red Mug"); // C# 7.2+
        PrintOrderDetails("Gift Shop", orderNum: 31, "Red Mug");                // C# 7.2+

        // The following statements will cause a compiler error.
        // PrintOrderDetails(productName: "Red Mug", 31, "Gift Shop");
    }

    static void PrintOrderDetails(string sellerName, int orderNum, string productName)
    {
        // some code here
    }
}

Optional Arguments

class OptionalExample
{
    static void Main(string[] args)
    {
        PrintOrderDetails("FIRMA s.r.o.", 31);
        
        PrintOrderDetails("FIRMA s.r.o.", 31, "Fakturujeme Vam na zaklade dohody");
    }

    static void PrintOrderDetails(string companyName, int orderNum, 
                                  string additionalInfo = "Fakturujeme Vam na zaklade objednavky:")
    {
        // some code here
    }
}

Delegates

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type.

public delegate void MessageDelegate(string message);

// Create a method for a delegate.
public static void DelegateMethod(string message)
{
    Console.WriteLine(message);
}

// Instantiate the delegate.
Del handler = DelegateMethod;

// Call the delegate.
handler("Hello World");


// Usual usecase
public static void MethodWithCallback(int param1, int param2, Del callback)
{
    callback("The number is: " + (param1 + param2).ToString());
}

Delegates

// And one nice usage with delegate arithmetics

var obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;

//Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;

Generic Delegates

Func<interest,double> calcSI = SIObj =>(SIObj.P*SIObj.T*SIObj.R)/100;

Interest obj = new Interest() { P = 120, T = 1, R = 3.25};
// Consuming delegate
var si = calcSI(obj);

Func

Action

Action<string> MyAction = y => Console.Write(y);
MyAction("Hello");

Predicate

Predicate<string> checkValidDate = d => IsDate(d);

Local Functions

class Example
{
    static void Main()
    {
        string contents = GetText(@"C:\temp", "example.txt");
        Console.WriteLine("Contents of the file:\n" + contents);
    }
   
    private static string GetText(string path, string filename)
    {
         var sr = File.OpenText(AppendPathSeparator(path) + filename);
         var text = sr.ReadToEnd();
         return text;
         
         // Declare a local function.
         string AppendPathSeparator(string filepath)
         {
            if (! filepath.EndsWith(@"\"))
               filepath += @"\";

            return filepath;   
         }
    } 
}

Events

Events are a way for an object to broadcast (to all interested components in the system) that something has happened. Any other component can subscribe to the event, and be notified when an event is raised.

public event EventHandler<FileListArgs> Progress;


EventHandler<FileListArgs> onProgress = (sender, eventArgs) =>
    Console.WriteLine(eventArgs.FoundFile);

fileLister.Progress += onProgress;

Events

public class FileFoundArgs : EventArgs
{
    public string FoundFile { get; }

    public FileFoundArgs(string fileName)
    {
        FoundFile = fileName;
    }
}

public class FileSearcher
{
    public event EventHandler<FileFoundArgs> FileFound;

    public void Search(string directory, string searchPattern)
    {
        foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
        {
            FileFound?.Invoke(this, new FileFoundArgs(file));
        }
    }
}

EventHandler<FileFoundArgs> onFileFound = (sender, eventArgs) =>
{
    Console.WriteLine(eventArgs.FoundFile);
    eventArgs.CancelRequested = true;
};

Extension Methods

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}

And usage afterwards

string s = "Hello Extension Methods";  
int i = s.WordCount();  

Why to use extension methods?

  • You don't have access to class source code
  • You don't want to modify the class
  • You don't want to use inheritance

slide was left intentionally blank

Let's try it. :)

Made with Slides.com