CSharp examples for Language Basics:Nullable
Check null field with ??
using System;/*from ww w . j ava 2 s.c o m*/ using System.Collections.Generic; using System.Text; public class FastRunner : Runnable { public void Run(int distance) { Console.WriteLine($"Running fast for {distance} kms"); } } public interface Runnable { void Run(int distance); } public class Person { public string FirstName { get; private set; } public string LastName { get; private set; } private Runnable _runner; public Person(string firstName, string lastName, Runnable runner) { FirstName = firstName; LastName = lastName; _runner = runner ?? throw new ArgumentNullException("runner"); } public void Run(int distance) { _runner.Run(distance); } } class Program { static void Main(string[] args) { try { Person p = new Person("John", "Smith", new SlowRunner()); p.Run(9); } catch(ArgumentNullException e) { Console.WriteLine("Runner cannot be null"); } catch(Exception e) { Console.WriteLine("Oops something went wrong"); } } } public class SlowRunner : Runnable { public void Run(int distance) { Console.WriteLine($"Running slow for {distance} kms"); } }