• No results found

C# Notes for Professionals

N/A
N/A
Protected

Academic year: 2021

Share "C# Notes for Professionals"

Copied!
807
0
0

Loading.... (view fulltext now)

Full text

(1)

C#

Notes for Professionals

C#

Notes for Professionals

GoalKicker.com

Free Programming Books

Disclaimer

This is an unocial free book created for educational purposes and is not aliated with ocial C# group(s) or company(s).

700+ pages

of professional hints and tricks

(2)

Contents

About

... 1

Chapter 1: Getting started with C# Language

... 2

Section 1.1: Creating a new console application (Visual Studio) ... 2

Section 1.2: Creating a new project in Visual Studio (console application) and Running it in Debug mode 4 ... Section 1.3: Creating a new program using .NET Core ... 7

Section 1.4: Creating a new program using Mono ... 9

Section 1.5: Creating a new query using LinqPad ... 9

Section 1.6: Creating a new project using Xamarin Studio ... 12

Chapter 2: Verbatim Strings

... 18

Section 2.1: Interpolated Verbatim Strings ... 18

Section 2.2: Escaping Double Quotes ... 18

Section 2.3: Verbatim strings instruct the compiler to not use character escapes ... 18

Section 2.4: Multiline Strings ... 19

Chapter 3: Operators

... 20

Section 3.1: Overloadable Operators ... 20

Section 3.2: Overloading equality operators ... 21

Section 3.3: Relational Operators ... 22

Section 3.4: Implicit Cast and Explicit Cast Operators ... 24

Section 3.5: Short-circuiting Operators ... 25

Section 3.6: ? : Ternary Operator ... 26

Section 3.7: ?. (Null Conditional Operator) ... 27

Section 3.8: "Exclusive or" Operator ... 27

Section 3.9: default Operator ... 27

Section 3.10: Assignment operator '=' ... 28

Section 3.11: sizeof ... 28

Section 3.12: ?? Null-Coalescing Operator ... 29

Section 3.13: Bit-Shifting Operators ... 29

Section 3.14: => Lambda operator ... 29

Section 3.15: Class Member Operators: Null Conditional Member Access ... 30

Section 3.16: Class Member Operators: Null Conditional Indexing ... 31

Section 3.17: Postfix and Prefix increment and decrement ... 31

Section 3.18: typeof ... 31

Section 3.19: Binary operators with assignment ... 32

Section 3.20: nameof Operator ... 32

Section 3.21: Class Member Operators: Member Access ... 32

Section 3.22: Class Member Operators: Function Invocation ... 33

Section 3.23: Class Member Operators: Aggregate Object Indexing ... 33

Chapter 4: Extension Methods

... 34

Section 4.1: Extension methods - overview ... 34

Section 4.2: Null checking ... 36

Section 4.3: Explicitly using an extension method ... 37

Section 4.4: Generic Extension Methods ... 37

Section 4.5: Extension methods can only see public (or internal) members of the extended class ... 39

Section 4.6: Extension methods for chaining ... 39

Section 4.7: Extension methods with Enumeration ... 40

(3)

Section 4.9: Extension methods on Interfaces ... 42

Section 4.10: Extension methods in combination with interfaces ... 43

Section 4.11: Extension methods aren't supported by dynamic code ... 43

Section 4.12: Extensions and interfaces together enable DRY code and mixin-like functionality ... 44

Section 4.13: IList<T> Extension Method Example: Comparing 2 Lists ... 45

Section 4.14: Extension methods as strongly typed wrappers ... 46

Section 4.15: Using Extension methods to create beautiful mapper classes ... 46

Section 4.16: Using Extension methods to build new collection types (e.g. DictList) ... 47

Section 4.17: Extension methods for handling special cases ... 48

Section 4.18: Using Extension methods with Static methods and Callbacks ... 49

Chapter 5: Collection Initializers

... 51

Section 5.1: Collection initializers ... 51

Section 5.2: C# 6 Index Initializers ... 51

Section 5.3: Collection initializers in custom classes ... 52

Section 5.4: Using collection initializer inside object initializer ... 53

Section 5.5: Collection Initializers with Parameter Arrays ... 54

Chapter 6: String Interpolation

... 55

Section 6.1: Format dates in strings ... 55

Section 6.2: Padding the output ... 55

Section 6.3: Expressions ... 56

Section 6.4: Formatting numbers in strings ... 56

Section 6.5: Simple Usage ... 57

Chapter 7: An overview of C# collections

... 58

Section 7.1: HashSet<T> ... 58

Section 7.2: Dictionary<TKey, TValue> ... 58

Section 7.3: SortedSet<T> ... 59 Section 7.4: T[ ] (Array of T) ... 59 Section 7.5: List<T> ... 60 Section 7.6: Stack<T> ... 60 Section 7.7: LinkedList<T> ... 60 Section 7.8: Queue ... 61

Chapter 8: Constructors and Finalizers

... 62

Section 8.1: Static constructor ... 62

Section 8.2: Singleton constructor pattern ... 63

Section 8.3: Default Constructor ... 63

Section 8.4: Forcing a static constructor to be called ... 64

Section 8.5: Calling a constructor from another constructor ... 65

Section 8.6: Calling the base class constructor ... 65

Section 8.7: Finalizers on derived classes ... 66

Section 8.8: Exceptions in static constructors ... 66

Section 8.9: Constructor and Property Initialization ... 67

Section 8.10: Generic Static Constructors ... 69

Section 8.11: Calling virtual methods in constructor ... 69

Chapter 9: Static Classes

... 71

Section 9.1: Static Classes ... 71

Section 9.2: Static class lifetime ... 71

Section 9.3: Static keyword ... 72

Chapter 10: Keywords

... 73

Section 10.1: as ... 73

(4)

Section 10.3: volatile ... 75

Section 10.4: checked, unchecked ... 76

Section 10.5: virtual, override, new ... 77

Section 10.6: stackalloc ... 80

Section 10.7: break ... 81

Section 10.8: const ... 83

Section 10.9: async, await ... 84

Section 10.10: for ... 85 Section 10.11: abstract ... 86 Section 10.12: fixed ... 87 Section 10.13: default ... 88 Section 10.14: sealed ... 89 Section 10.15: is ... 89 Section 10.16: this ... 90 Section 10.17: readonly ... 91 Section 10.18: typeof ... 92 Section 10.19: foreach ... 92 Section 10.20: dynamic ... 93

Section 10.21: try, catch, finally, throw ... 94

Section 10.22: void ... 95

Section 10.23: namespace ... 95

Section 10.24: ref, out ... 96

Section 10.25: base ... 97

Section 10.26: float, double, decimal ... 99

Section 10.27: operator ... 100 Section 10.28: char ... 101 Section 10.29: params ... 101 Section 10.30: while ... 102 Section 10.31: null ... 104 Section 10.32: continue ... 105 Section 10.33: string ... 105 Section 10.34: return ... 106 Section 10.35: unsafe ... 106 Section 10.36: switch ... 108 Section 10.37: var ... 109 Section 10.38: when ... 110 Section 10.39: lock ... 111 Section 10.40: uint ... 112

Section 10.41: if, if...else, if... else if ... 112

Section 10.42: static ... 113 Section 10.43: internal ... 115 Section 10.44: using ... 116 Section 10.45: where ... 116 Section 10.46: int ... 118 Section 10.47: ulong ... 119

Section 10.48: true, false ... 119

Section 10.49: struct ... 119

Section 10.50: extern ... 120

Section 10.51: bool ... 121

Section 10.52: interface ... 121

(5)

Section 10.54: unchecked ... 122 Section 10.55: ushort ... 123 Section 10.56: sizeof ... 123 Section 10.57: in ... 123 Section 10.58: implicit ... 124 Section 10.59: do ... 124 Section 10.60: long ... 125 Section 10.61: enum ... 125 Section 10.62: partial ... 126 Section 10.63: event ... 127 Section 10.64: sbyte ... 128

Chapter 11: Object Oriented Programming In C#

... 129

Section 11.1: Classes: ... 129

Chapter 12: Inheritance

... 130

Section 12.1: Inheritance. Constructors' calls sequence ... 130

Section 12.2: Inheriting from a base class ... 132

Section 12.3: Inheriting from a class and implementing an interface ... 133

Section 12.4: Inheriting from a class and implementing multiple interfaces ... 133

Section 12.5: Constructors In A Subclass ... 134

Section 12.6: Inheritance Anti-patterns ... 134

Section 12.7: Extending an abstract base class ... 135

Section 12.8: Testing and navigating inheritance ... 136

Section 12.9: Inheriting methods ... 136

Section 12.10: Base class with recursive type specification ... 137

Chapter 13: Generics

... 140

Section 13.1: Implicit type inference (methods) ... 140

Section 13.2: Type inference (classes) ... 141

Section 13.3: Using generic method with an interface as a constraint type ... 141

Section 13.4: Type constraints (new-keyword) ... 142

Section 13.5: Type constraints (classes and interfaces) ... 143

Section 13.6: Checking equality of generic values ... 144

Section 13.7: Reflecting on type parameters ... 145

Section 13.8: Covariance ... 145

Section 13.9: Contravariance ... 146

Section 13.10: Invariance ... 147

Section 13.11: Variant interfaces ... 147

Section 13.12: Variant delegates ... 148

Section 13.13: Variant types as parameters and return values ... 149

Section 13.14: Type Parameters (Interfaces) ... 149

Section 13.15: Type constraints (class and struct) ... 150

Section 13.16: Explicit type parameters ... 150

Section 13.17: Type Parameters (Classes) ... 150

Section 13.18: Type Parameters (Methods) ... 151

Section 13.19: Generic type casting ... 151

Section 13.20: Configuration reader with generic type casting ... 152

Chapter 14: Using Statement

... 154

Section 14.1: Using Statement Basics ... 154

Section 14.2: Gotcha: returning the resource which you are disposing ... 155

Section 14.3: Multiple using statements with one block ... 156

(6)

Section 14.5: Using statements are null-safe ... 157

Section 14.6: Using Dispose Syntax to define custom scope ... 157

Section 14.7: Using Statements and Database Connections ... 158

Section 14.8: Executing code in constraint context ... 160

Chapter 15: Using Directive

... 161

Section 15.1: Associate an Alias to Resolve Conflicts ... 161

Section 15.2: Using alias directives ... 161

Section 15.3: Access Static Members of a Class ... 161

Section 15.4: Basic Usage ... 162

Section 15.5: Reference a Namespace ... 162

Section 15.6: Associate an Alias with a Namespace ... 162

Chapter 16: Reflection

... 164

Section 16.1: Get the members of a type ... 164

Section 16.2: Get a method and invoke it ... 164

Section 16.3: Creating an instance of a Type ... 165

Section 16.4: Get a Strongly-Typed Delegate to a Method or Property via Reflection ... 168

Section 16.5: Get a generic method and invoke it ... 169

Section 16.6: Get a System.Type ... 170

Section 16.7: Getting and setting properties ... 170

Section 16.8: Create an instance of a Generic Type and invoke it's method ... 170

Section 16.9: Custom Attributes ... 170

Section 16.10: Instantiating classes that implement an interface (e.g. plugin activation) ... 172

Section 16.11: Get a Type by name with namespace ... 172

Section 16.12: Determining generic arguments of instances of generic types ... 173

Section 16.13: Looping through all the properties of a class ... 174

Chapter 17: Null-Coalescing Operator

... 175

Section 17.1: Basic usage ... 175

Section 17.2: Null fall-through and chaining ... 175

Section 17.3: Null coalescing operator with method calls ... 176

Section 17.4: Use existing or create new ... 177

Section 17.5: Lazy properties initialization with null coalescing operator ... 177

Chapter 18: Getting Started: Json with C#

... 178

Section 18.1: Simple Json Example ... 178

Section 18.2: First things First: Library to work with Json ... 178

Section 18.3: C# Implementation ... 178

Section 18.4: Serialization ... 179

Section 18.5: Deserialization ... 179

Section 18.6: Serialization & De-Serialization Common Utilities function ... 179

Chapter 19: LINQ Queries

... 181

Section 19.1: Chaining methods ... 181

Section 19.2: First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault ... 182

Section 19.3: Except ... 185

Section 19.4: SelectMany ... 187

Section 19.5: Any ... 188

Section 19.6: JOINS ... 188

Section 19.7: Skip and Take ... 191

Section 19.8: Defining a variable inside a Linq query (let keyword) ... 191

Section 19.9: Zip ... 192

Section 19.10: Range and Repeat ... 192

(7)

Section 19.12: All ... 193

Section 19.13: Aggregate ... 194

Section 19.14: Distinct ... 195

Section 19.15: SelectMany: Flattening a sequence of sequences ... 195

Section 19.16: GroupBy ... 197

Section 19.17: Query collection by type / cast elements to type ... 198

Section 19.18: Enumerating the Enumerable ... 198

Section 19.19: Using Range with various Linq methods ... 200

Section 19.20: Where ... 200

Section 19.21: Using SelectMany instead of nested loops ... 201

Section 19.22: Contains ... 201

Section 19.23: Joining multiple sequences ... 202

Section 19.24: Joining on multiple keys ... 204

Section 19.25: ToLookup ... 205

Section 19.26: SkipWhile ... 205

Section 19.27: Query Ordering - OrderBy() ThenBy() OrderByDescending() ThenByDescending() ... 205

Section 19.28: Sum ... 206

Section 19.29: GroupBy one or multiple fields ... 207

Section 19.30: OrderBy ... 207

Section 19.31: Any and First(OrDefault) - best practice ... 208

Section 19.32: GroupBy Sum and Count ... 209

Section 19.33: SequenceEqual ... 210

Section 19.34: ElementAt and ElementAtOrDefault ... 210

Section 19.35: DefaultIfEmpty ... 210

Section 19.36: ToDictionary ... 212

Section 19.37: Concat ... 212

Section 19.38: Build your own Linq operators for IEnumerable<T> ... 213

Section 19.39: Select - Transforming elements ... 214

Section 19.40: OrderByDescending ... 214

Section 19.41: Union ... 215

Section 19.42: GroupJoin with outer range variable ... 215

Section 19.43: Linq Quantifiers ... 215

Section 19.44: TakeWhile ... 216

Section 19.45: Reverse ... 216

Section 19.46: Count and LongCount ... 217

Section 19.47: Incrementally building a query ... 217

Section 19.48: Select with Func<TSource, int, TResult> selector - Use to get ranking of elements ... 219

Chapter 20: C# 7.0 Features

... 221

Section 20.1: Language support for Tuples ... 221

Section 20.2: Local functions ... 225

Section 20.3: out var declaration ... 226

Section 20.4: Pattern Matching ... 227

Section 20.5: Digit separators ... 229

Section 20.6: Binary literals ... 229

Section 20.7: throw expressions ... 230

Section 20.8: Extended expression bodied members list ... 231

Section 20.9: ref return and ref local ... 232

Section 20.10: ValueTask<T> ... 233

Chapter 21: C# 6.0 Features

... 235

(8)

Section 21.2: String interpolation ... 239

Section 21.3: Auto-property initializers ... 245

Section 21.4: Null propagation ... 247

Section 21.5: Expression-bodied function members ... 250

Section 21.6: Operator nameof ... 252

Section 21.7: Using static type ... 254

Section 21.8: Index initializers ... 254

Section 21.9: Improved overload resolution ... 256

Section 21.10: Await in catch and finally ... 257

Section 21.11: Minor changes and bugfixes ... 258

Section 21.12: Using an extension method for collection initialization ... 259

Section 21.13: Disable Warnings Enhancements ... 260

Chapter 22: C# 5.0 Features

... 261

Section 22.1: Async & Await ... 261

Section 22.2: Caller Information Attributes ... 262

Chapter 23: C# 4.0 Features

... 263

Section 23.1: Optional parameters and named arguments ... 263

Section 23.2: Variance ... 264

Section 23.3: Dynamic member lookup ... 264

Section 23.4: Optional ref keyword when using COM ... 265

Chapter 24: C# 3.0 Features

... 266

Section 24.1: Implicitly typed variables (var) ... 266

Section 24.2: Language Integrated Queries (LINQ) ... 266

Section 24.3: Lambda expresions ... 267

Section 24.4: Anonymous types ... 267

Chapter 25: String Escape Sequences

... 269

Section 25.1: Escaping special symbols in string literals ... 269

Section 25.2: Unicode character escape sequences ... 269

Section 25.3: Escaping special symbols in character literals ... 269

Section 25.4: Using escape sequences in identifiers ... 269

Section 25.5: Unrecognized escape sequences produce compile-time errors ... 270

Chapter 26: Exception Handling

... 271

Section 26.1: Creating Custom Exceptions ... 271

Section 26.2: Finally block ... 273

Section 26.3: Best Practices ... 274

Section 26.4: Exception Anti-patterns ... 276

Section 26.5: Basic Exception Handling ... 278

Section 26.6: Handling specific exception types ... 278

Section 26.7: Aggregate exceptions / multiple exceptions from one method ... 279

Section 26.8: Throwing an exception ... 280

Section 26.9: Unhandled and Thread Exception ... 280

Section 26.10: Implementing IErrorHandler for WCF Services ... 281

Section 26.11: Using the exception object ... 283

Section 26.12: Nesting of Exceptions & try catch blocks ... 285

Chapter 27: Null-conditional Operators

... 286

Section 27.1: Null-Conditional Operator ... 286

Section 27.2: The Null-Conditional Index ... 286

Section 27.3: Avoiding NullReferenceExceptions ... 287

(9)

Chapter 28: Built-in Types

... 289

Section 28.1: Conversion of boxed value types ... 289

Section 28.2: Comparisons with boxed value types ... 289

Section 28.3: Immutable reference type - string ... 289

Section 28.4: Value type - char ... 290

Section 28.5: Value type - short, int, long (signed 16 bit, 32 bit, 64 bit integers) ... 290

Section 28.6: Value type - ushort, uint, ulong (unsigned 16 bit, 32 bit, 64 bit integers) ... 290

Section 28.7: Value type - bool ... 291

Chapter 29: Lambda expressions

... 292

Section 29.1: Lambda Expressions as Shorthand for Delegate Initialization ... 292

Section 29.2: Lambda Expression as an Event Handler ... 292

Section 29.3: Lambda Expressions with Multiple Parameters or No Parameters ... 293

Section 29.4: Lambdas can be emitted both as `Func` and `Expression` ... 293

Section 29.5: Put Multiple Statements in a Statement Lambda ... 293

Section 29.6: Lambdas for both `Func` and `Action` ... 294

Section 29.7: Passing a Lambda Expression as a Parameter to a Method ... 294

Chapter 30: Async-Await

... 295

Section 30.1: Await operator and async keyword ... 295

Section 30.2: Concurrent calls ... 296

Section 30.3: Try/Catch/Finally ... 297

Section 30.4: Returning a Task without await ... 298

Section 30.5: Async/await will only improve performance if it allows the machine to do additional work 298 ... Section 30.6: Web.config setup to target 4.5 for correct async behaviour ... 299

Section 30.7: Simple consecutive calls ... 299

Section 30.8: Blocking on async code can cause deadlocks ... 300

Chapter 31: Properties

... 302

Section 31.1: Auto-implemented properties ... 302

Section 31.2: Default Values for Properties ... 302

Section 31.3: Public Get ... 303

Section 31.4: Public Set ... 303

Section 31.5: Accessing Properties ... 303

Section 31.6: Read-only properties ... 305

Section 31.7: Various Properties in Context ... 305

Chapter 32: Threading

... 307

Section 32.1: Avoiding Reading and Writing Data Simultaneously ... 307

Section 32.2: Creating and Starting a Second Thread ... 308

Section 32.3: Parallel.ForEach Loop ... 308

Section 32.4: Deadlocks (hold resource and wait) ... 309

Section 32.5: Simple Complete Threading Demo ... 311

Section 32.6: Creating One Thread Per Processor ... 312

Section 32.7: Simple Complete Threading Demo using Tasks ... 312

Section 32.8: Deadlocks (two threads waiting on each other) ... 313

Section 32.9: Explicit Task Parallism ... 314

Section 32.10: Implicit Task Parallelism ... 314

Section 32.11: Starting a thread with parameters ... 315

Chapter 33: Methods

... 316

Section 33.1: Calling a Method ... 316

Section 33.2: Anonymous method ... 316

(10)

Section 33.4: Parameters and Arguments ... 317

Section 33.5: Return Types ... 317

Section 33.6: Default Parameters ... 318

Section 33.7: Method overloading ... 319

Section 33.8: Access rights ... 320

Chapter 34: Yield Keyword

... 321

Section 34.1: Simple Usage ... 321

Section 34.2: Correctly checking arguments ... 321

Section 34.3: Early Termination ... 322

Section 34.4: More Pertinent Usage ... 323

Section 34.5: Lazy Evaluation ... 324

Section 34.6: Try...finally ... 325

Section 34.7: Eager evaluation ... 326

Section 34.8: Using yield to create an IEnumerator<T> when implementing IEnumerable<T> ... 326

Section 34.9: Lazy Evaluation Example: Fibonacci Numbers ... 327

Section 34.10: The dierence between break and yield break ... 328

Section 34.11: Return another Enumerable within a method returning Enumerable ... 329

Chapter 35: Events

... 330

Section 35.1: Declaring and Raising Events ... 330

Section 35.2: Event Properties ... 331

Section 35.3: Creating cancelable event ... 332

Section 35.4: Standard Event Declaration ... 333

Section 35.5: Anonymous Event Handler Declaration ... 334

Section 35.6: Non-Standard Event Declaration ... 334

Section 35.7: Creating custom EventArgs containing additional data ... 335

Chapter 36: Common String Operations

... 337

Section 36.1: Formatting a string ... 337

Section 36.2: Correctly reversing a string ... 337

Section 36.3: Padding a string to a fixed length ... 338

Section 36.4: Getting x characters from the right side of a string ... 339

Section 36.5: Checking for empty String using String.IsNullOrEmpty() and String.IsNullOrWhiteSpace() 340 ... Section 36.6: Trimming Unwanted Characters O the Start and/or End of Strings ... 341

Section 36.7: Convert Decimal Number to Binary,Octal and Hexadecimal Format ... 341

Section 36.8: Construct a string from Array ... 341

Section 36.9: Formatting using ToString ... 342

Section 36.10: Splitting a String by another string ... 343

Section 36.11: Splitting a String by specific character ... 343

Section 36.12: Getting Substrings of a given string ... 343

Section 36.13: Determine whether a string begins with a given sequence ... 343

Section 36.14: Getting a char at specific index and enumerating the string ... 343

Section 36.15: Joining an array of strings into a new one ... 344

Section 36.16: Replacing a string within a string ... 344

Section 36.17: Changing the case of characters within a String ... 344

Section 36.18: Concatenate an array of strings into a single string ... 345

Section 36.19: String Concatenation ... 345

Chapter 37: Expression Trees

... 346

Section 37.1: Create Expression Trees with a lambda expression ... 346

Section 37.2: Creating Expression Trees by Using the API ... 346

(11)

Section 37.4: Parsing Expression Trees ... 347

Section 37.5: Expression Tree Basic ... 347

Section 37.6: Examining the Structure of an Expression using Visitor ... 348

Section 37.7: Understanding the expressions API ... 348

Chapter 38: Overload Resolution

... 350

Section 38.1: Basic Overloading Example ... 350

Section 38.2: "params" is not expanded, unless necessary ... 350

Section 38.3: Passing null as one of the arguments ... 351

Chapter 39: String.Format

... 352

Section 39.1: Since C# 6.0 ... 352

Section 39.2: Places where String.Format is 'embedded' in the framework ... 352

Section 39.3: Create a custom format provider ... 352

Section 39.4: Date Formatting ... 353

Section 39.5: Currency Formatting ... 354

Section 39.6: Using custom number format ... 355

Section 39.7: Align left/ right, pad with spaces ... 355

Section 39.8: Numeric formats ... 355

Section 39.9: ToString() ... 356

Section 39.10: Escaping curly brackets inside a String.Format() expression ... 356

Section 39.11: Relationship with ToString() ... 356

Chapter 40: nameof Operator

... 358

Section 40.1: Basic usage: Printing a variable name ... 358

Section 40.2: Raising PropertyChanged event ... 358

Section 40.3: Argument Checking and Guard Clauses ... 359

Section 40.4: Strongly typed MVC action links ... 359

Section 40.5: Handling PropertyChanged events ... 360

Section 40.6: Applied to a generic type parameter ... 360

Section 40.7: Printing a parameter name ... 361

Section 40.8: Applied to qualified identifiers ... 361

Chapter 41: Unsafe Code in .NET

... 362

Section 41.1: Using unsafe with arrays ... 362

Section 41.2: Using unsafe with strings ... 362

Section 41.3: Unsafe Array Index ... 363

Chapter 42: Initializing Properties

... 364

Section 42.1: C# 6.0: Initialize an Auto-Implemented Property ... 364

Section 42.2: Initializing Property with a Backing Field ... 364

Section 42.3: Property Initialization during object instantiation ... 364

Section 42.4: Initializing Property in Constructor ... 364

Chapter 43: BindingList<T>

... 365

Section 43.1: Add item to list ... 365

Section 43.2: Avoiding N*2 iteration ... 365

Chapter 44: ILGenerator

... 366

Section 44.1: Creates a DynamicAssembly that contains a UnixTimestamp helper method ... 366

Section 44.2: Create method override ... 367

Chapter 45: Object initializers

... 369

Section 45.1: Simple usage ... 369

Section 45.2: Usage with non-default constructors ... 369

Section 45.3: Usage with anonymous types ... 369

(12)

Section 46.1: Simple method annotation ... 371

Section 46.2: Generating XML from documentation comments ... 371

Section 46.3: Method documentation comment with param and returns elements ... 373

Section 46.4: Interface and class documentation comments ... 373

Section 46.5: Referencing another class in documentation ... 374

Chapter 47: Preprocessor directives

... 375

Section 47.1: Conditional Expressions ... 375

Section 47.2: Other Compiler Instructions ... 375

Section 47.3: Defining and Undefining Symbols ... 376

Section 47.4: Region Blocks ... 377

Section 47.5: Disabling and Restoring Compiler Warnings ... 377

Section 47.6: Generating Compiler Warnings and Errors ... 377

Section 47.7: Custom Preprocessors at project level ... 378

Section 47.8: Using the Conditional attribute ... 378

Chapter 48: Dynamic type

... 380

Section 48.1: Creating a dynamic object with properties ... 380

Section 48.2: Creating a dynamic variable ... 380

Section 48.3: Returning dynamic ... 380

Section 48.4: Handling Specific Types Unknown at Compile Time ... 380

Chapter 49: Anonymous types

... 382

Section 49.1: Anonymous vs dynamic ... 382

Section 49.2: Creating an anonymous type ... 382

Section 49.3: Anonymous type equality ... 382

Section 49.4: Generic methods with anonymous types ... 383

Section 49.5: Instantiating generic types with anonymous types ... 383

Section 49.6: Implicitly typed arrays ... 383

Chapter 50: Structs

... 385

Section 50.1: Declaring a struct ... 385

Section 50.2: Struct usage ... 386

Section 50.3: Structs are copied on assignment ... 387

Section 50.4: Struct implementing interface ... 387

Chapter 51: Tuples

... 388

Section 51.1: Accessing tuple elements ... 388

Section 51.2: Creating tuples ... 388

Section 51.3: Comparing and sorting Tuples ... 388

Section 51.4: Return multiple values from a method ... 389

Chapter 52: Enum

... 390

Section 52.1: Enum basics ... 390

Section 52.2: Enum as flags ... 391

Section 52.3: Using << notation for flags ... 393

Section 52.4: Test flags-style enum values with bitwise logic ... 393

Section 52.5: Add and remove values from flagged enum ... 394

Section 52.6: Enum to string and back ... 394

Section 52.7: Enums can have unexpected values ... 395

Section 52.8: Default value for enum == ZERO ... 395

Section 52.9: Adding additional description information to an enum value ... 396

Section 52.10: Get all the members values of an enum ... 397

Section 52.11: Bitwise Manipulation using enums ... 397

(13)

Section 53.1: Access Modifiers Diagrams ... 398

Section 53.2: public ... 399

Section 53.3: private ... 399

Section 53.4: protected internal ... 400

Section 53.5: internal ... 401

Section 53.6: protected ... 402

Chapter 54: Task Parallel Library

... 403

Section 54.1: Parallel.ForEach ... 403

Section 54.2: Parallel.For ... 403

Section 54.3: Parallel.Invoke ... 404

Chapter 55: Attributes

... 405

Section 55.1: Creating a custom attribute ... 405

Section 55.2: Reading an attribute ... 405

Section 55.3: Using an attribute ... 406

Section 55.4: DebuggerDisplay Attribute ... 406

Section 55.5: Caller info attributes ... 407

Section 55.6: Obsolete Attribute ... 408

Section 55.7: Reading an attribute from interface ... 408

Chapter 56: Guid

... 410

Section 56.1: Getting the string representation of a Guid ... 410

Section 56.2: Creating a Guid ... 410

Section 56.3: Declaring a nullable GUID ... 410

Chapter 57: Singleton Implementation

... 412

Section 57.1: Statically Initialized Singleton ... 412

Section 57.2: Lazy, thread-safe Singleton (using Lazy<T>) ... 412

Section 57.3: Lazy, thread-safe Singleton (using Double Checked Locking) ... 412

Section 57.4: Lazy, thread safe singleton (for .NET 3.5 or older, alternate implementation) ... 413

Chapter 58: Delegates

... 415

Section 58.1: Declaring a delegate type ... 415

Section 58.2: The Func<T, TResult>, Action<T> and Predicate<T> delegate types ... 416

Section 58.3: Combine Delegates (Multicast Delegates) ... 417

Section 58.4: Safe invoke multicast delegate ... 418

Section 58.5: Delegate Equality ... 419

Section 58.6: Underlying references of named method delegates ... 419

Section 58.7: Assigning a named method to a delegate ... 420

Section 58.8: Assigning to a delegate by lambda ... 421

Section 58.9: Encapsulating transformations in funcs ... 421

Section 58.10: Passing delegates as parameters ... 421

Section 58.11: Closure inside a delegate ... 422

Chapter 59: Nullable types

... 423

Section 59.1: Initialising a nullable ... 423

Section 59.2: Check if a Nullable has a value ... 423

Section 59.3: Get the value of a nullable type ... 423

Section 59.4: Getting a default value from a nullable ... 424

Section 59.5: Default value of nullable types is null ... 424

Section 59.6: Eective usage of underlying Nullable<T> argument ... 425

Section 59.7: Check if a generic type parameter is a nullable type ... 426

Chapter 60: Garbage Collector in .Net

... 427

(14)

Section 60.2: Large Object Heap compaction ... 428

Chapter 61: Networking

... 429

Section 61.1: Basic TCP Communication Client ... 429

Section 61.2: Download a file from a web server ... 429

Section 61.3: Async TCP Client ... 430

Section 61.4: Basic UDP Client ... 431

Chapter 62: Arrays

... 432

Section 62.1: Declaring an array ... 432

Section 62.2: Initializing an array filled with a repeated non-default value ... 432

Section 62.3: Copying arrays ... 433

Section 62.4: Comparing arrays for equality ... 433

Section 62.5: Multi-dimensional arrays ... 434

Section 62.6: Getting and setting array values ... 434

Section 62.7: Iterate over an array ... 434

Section 62.8: Creating an array of sequential numbers ... 435

Section 62.9: Jagged arrays ... 435

Section 62.10: Array covariance ... 437

Section 62.11: Arrays as IEnumerable<> instances ... 437

Section 62.12: Checking if one array contains another array ... 437

Chapter 63: Equality Operator

... 439

Section 63.1: Equality kinds in c# and equality operator ... 439

Chapter 64: Lock Statement

... 440

Section 64.1: Throwing exception in a lock statement ... 440

Section 64.2: Simple usage ... 440

Section 64.3: Return in a lock statement ... 441

Section 64.4: Anti-Patterns and gotchas ... 441

Section 64.5: Using instances of Object for lock ... 445

Chapter 65: Action Filters

... 446

Section 65.1: Custom Action Filters ... 446

Chapter 66: XmlDocument and the System.Xml namespace

... 447

Section 66.1: XmlDocument vs XDocument (Example and comparison) ... 447

Section 66.2: Reading from XML document ... 449

Section 66.3: Basic XML document interaction ... 450

Chapter 67: DateTime Methods

... 451

Section 67.1: DateTime Formating ... 451

Section 67.2: DateTime.AddDays(Double) ... 452

Section 67.3: DateTime.AddHours(Double) ... 452

Section 67.4: DateTime.Parse(String) ... 452

Section 67.5: DateTime.TryParse(String, DateTime) ... 452

Section 67.6: DateTime.AddMilliseconds(Double) ... 453

Section 67.7: DateTime.Compare(DateTime t1, DateTime t2 ) ... 453

Section 67.8: DateTime.DaysInMonth(Int32,?Int32) ... 453

Section 67.9: DateTime.AddYears(Int32) ... 454

Section 67.10: Pure functions warning when dealing with DateTime ... 454

Section 67.11: DateTime.TryParseExact(String,?String,?IFormatProvider,?DateTimeStyles,?DateTime) 454 ... Section 67.12: DateTime.Add(TimeSpan) ... 456

Section 67.13: Parse and TryParse with culture info ... 456

(15)

Section 67.15: DateTime.ParseExact(String,?String,?IFormatProvider) ... 457

Section 67.16: DateTime ToString, ToShortDateString, ToLongDateString and ToString formatted ... 458

Section 67.17: Current Date ... 458

Chapter 68: BackgroundWorker

... 459

Section 68.1: Using a BackgroundWorker to complete a task ... 459

Section 68.2: Assigning Event Handlers to a BackgroundWorker ... 460

Section 68.3: Creating a new BackgroundWorker instance ... 461

Section 68.4: Assigning Properties to a BackgroundWorker ... 461

Chapter 69: Polymorphism

... 462

Section 69.1: Types of Polymorphism ... 462

Section 69.2: Another Polymorphism Example ... 463

Chapter 70: Indexer

... 466

Section 70.1: A simple indexer ... 466

Section 70.2: Overloading the indexer to create a SparseArray ... 466

Section 70.3: Indexer with 2 arguments and interface ... 467

Chapter 71: IDisposable interface

... 468

Section 71.1: In a class that contains only managed resources ... 468

Section 71.2: In a class with managed and unmanaged resources ... 468

Section 71.3: IDisposable, Dispose ... 469

Section 71.4: using keyword ... 469

Section 71.5: In an inherited class with managed resources ... 470

Chapter 72: Aliases of built-in types

... 471

Section 72.1: Built-In Types Table ... 471

Chapter 73: Immutability

... 472

Section 73.1: System.String class ... 472

Section 73.2: Strings and immutability ... 472

Chapter 74: XDocument and the System.Xml.Linq namespace

... 473

Section 74.1: Generate an XML document ... 473

Section 74.2: Generate an XML document using fluent syntax ... 473

Section 74.3: Modify XML File ... 474

Chapter 75: Performing HTTP requests

... 476

Section 75.1: Creating and sending an HTTP POST request ... 476

Section 75.2: Creating and sending an HTTP GET request ... 476

Section 75.3: Error handling of specific HTTP response codes (such as 404 Not Found) ... 477

Section 75.4: Retrieve HTML for Web Page (Simple) ... 477

Section 75.5: Sending asynchronous HTTP POST request with JSON body ... 477

Chapter 76: Generating Random Numbers in C#

... 479

Section 76.1: Generate a random int ... 479

Section 76.2: Generate a random int in a given range ... 479

Section 76.3: Generating the same sequence of random numbers over and over again ... 479

Section 76.4: Create multiple random class with dierent seeds simultaneously ... 479

Section 76.5: Generate a Random double ... 480

Section 76.6: Generate a random character ... 480

Section 76.7: Generate a number that is a percentage of a max value ... 480

Chapter 77: Looping

... 482

Section 77.1: For Loop ... 482

Section 77.2: Do - While Loop ... 483

Section 77.3: Foreach Loop ... 483

(16)

Section 77.5: Nested loops ... 485

Section 77.6: continue ... 485

Section 77.7: While loop ... 486

Section 77.8: break ... 486

Chapter 78: Named Arguments

... 488

Section 78.1: Argument order is not necessary ... 488

Section 78.2: Named arguments and optional paramaters ... 488

Section 78.3: Named Arguments can make your code more clear ... 488

Chapter 79: Diagnostics

... 490

Section 79.1: Redirecting log output with TraceListeners ... 490

Section 79.2: Debug.WriteLine ... 490

Chapter 80: Interfaces

... 491

Section 80.1: Implementing an interface ... 491

Section 80.2: Explicit interface implementation ... 491

Section 80.3: Interface Basics ... 493

Section 80.4: IComparable<T> as an Example of Implementing an Interface ... 495

Section 80.5: Implementing multiple interfaces ... 496

Section 80.6: Why we use interfaces ... 496

Section 80.7: "Hiding" members with Explicit Implementation ... 497

Chapter 81: IEnumerable

... 499

Section 81.1: IEnumerable with custom Enumerator ... 499

Section 81.2: IEnumerable<int> ... 500

Chapter 82: Naming Conventions

... 501

Section 82.1: Capitalization conventions ... 501

Section 82.2: Enums ... 501

Section 82.3: Interfaces ... 502

Section 82.4: Exceptions ... 502

Section 82.5: Private fields ... 502

Section 82.6: Namespaces ... 503

Chapter 83: Checked and Unchecked

... 504

Section 83.1: Checked and Unchecked ... 504

Section 83.2: Checked and Unchecked as a scope ... 504

Chapter 84: Recursion

... 505

Section 84.1: Recursion in plain English ... 505

Section 84.2: Fibonacci Sequence ... 505

Section 84.3: PowerOf calculation ... 506

Section 84.4: Recursively describe an object structure ... 506

Section 84.5: Using Recursion to Get Directory Tree ... 507

Section 84.6: Factorial calculation ... 510

Chapter 85: Functional Programming

... 511

Section 85.1: Func and Action ... 511

Section 85.2: Higher-Order Functions ... 511

Section 85.3: Avoid Null References ... 511

Section 85.4: Immutability ... 513

Section 85.5: Immutable collections ... 514

Chapter 86: Literals

... 515

Section 86.1: uint literals ... 515

Section 86.2: int literals ... 515

(17)

Section 86.4: decimal literals ... 515

Section 86.5: double literals ... 515

Section 86.6: float literals ... 515

Section 86.7: long literals ... 515

Section 86.8: ulong literal ... 515

Section 86.9: string literals ... 516

Section 86.10: char literals ... 516

Section 86.11: byte literals ... 516

Section 86.12: short literal ... 516

Section 86.13: ushort literal ... 516

Section 86.14: bool literals ... 516

Chapter 87: Casting

... 517

Section 87.1: Checking compatibility without casting ... 517

Section 87.2: Cast an object to a base type ... 517

Section 87.3: Conversion Operators ... 517

Section 87.4: LINQ Casting operations ... 519

Section 87.5: Explicit Casting ... 519

Section 87.6: Safe Explicit Casting (`as` operator) ... 519

Section 87.7: Implicit Casting ... 520

Section 87.8: Explicit Numeric Conversions ... 520

Chapter 88: NullReferenceException

... 521

Section 88.1: NullReferenceException explained ... 521

Chapter 89: Func delegates

... 522

Section 89.1: Without parameters ... 522

Section 89.2: With multiple variables ... 522

Section 89.3: Lambda & anonymous methods ... 523

Section 89.4: Covariant & Contravariant Type Parameters ... 523

Chapter 90: LINQ to XML

... 525

Section 90.1: Read XML using LINQ to XML ... 525

Chapter 91: Hash Functions

... 527

Section 91.1: PBKDF2 for Password Hashing ... 527

Section 91.2: Complete Password Hashing Solution using Pbkdf2 ... 527

Section 91.3: MD5 ... 531

Section 91.4: SHA1 ... 531

Section 91.5: SHA256 ... 532

Section 91.6: SHA384 ... 532

Section 91.7: SHA512 ... 533

Chapter 92: Handling FormatException when converting string to other types

... 534

Section 92.1: Converting string to integer ... 534

Chapter 93: Cryptography (System.Security.Cryptography)

... 536

Section 93.1: Modern Examples of Symmetric Authenticated Encryption of a string ... 536

Section 93.2: Introduction to Symmetric and Asymmetric Encryption ... 547

Section 93.3: Simple Symmetric File Encryption ... 548

Section 93.4: Cryptographically Secure Random Data ... 549

Section 93.5: Password Hashing ... 550

Section 93.6: Fast Asymmetric File Encryption ... 550

Chapter 94: INotifyPropertyChanged interface

... 555

Section 94.1: Implementing INotifyPropertyChanged in C# 6 ... 555

(18)

Chapter 95: Value type vs Reference type

... 558

Section 95.1: Passing by reference using ref keyword ... 558

Section 95.2: Changing values elsewhere ... 559

Section 95.3: ref vs out parameters ... 560

Section 95.4: Assignment ... 561

Section 95.5: Dierence with method parameters ref and out ... 561

Section 95.6: Passing by reference ... 562

Chapter 96: IQueryable interface

... 563

Section 96.1: Translating a LINQ query to a SQL query ... 563

Chapter 97: Task Parallel Library (TPL) Dataflow Constructs

... 564

Section 97.1: ActionBlock<T> ... 564 Section 97.2: BroadcastBlock<T> ... 564 Section 97.3: BuerBlock<T> ... 565 Section 97.4: JoinBlock<T1, T2,…> ... 566 Section 97.5: WriteOnceBlock<T> ... 567 Section 97.6: BatchedJoinBlock<T1, T2,…> ... 568

Section 97.7: TransformBlock<TInput, TOutput> ... 569

Section 97.8: TransformManyBlock<TInput, TOutput> ... 569

Section 97.9: BatchBlock<T> ... 570

Chapter 98: Stream

... 572

Section 98.1: Using Streams ... 572

Chapter 99: Runtime Compile

... 574

Section 99.1: RoslynScript ... 574

Section 99.2: CSharpCodeProvider ... 574

Chapter 100: Conditional Statements

... 575

Section 100.1: If-Else Statement ... 575

Section 100.2: If statement conditions are standard boolean expressions and values ... 575

Section 100.3: If-Else If-Else Statement ... 576

Chapter 101: Interoperability

... 577

Section 101.1: Import function from unmanaged C++ DLL ... 577

Section 101.2: Calling conventions ... 577

Section 101.3: C++ name mangling ... 578

Section 101.4: Dynamic loading and unloading of unmanaged DLLs ... 578

Section 101.5: Reading structures with Marshal ... 579

Section 101.6: Dealing with Win32 Errors ... 580

Section 101.7: Pinned Object ... 581

Section 101.8: Simple code to expose class for com ... 582

Chapter 102: Overflow

... 584

Section 102.1: Integer overflow ... 584

Section 102.2: Overflow during operation ... 584

Section 102.3: Ordering matters ... 584

Chapter 103: Equals and GetHashCode

... 585

Section 103.1: Writing a good GetHashCode override ... 585

Section 103.2: Default Equals behavior ... 585

Section 103.3: Override Equals and GetHashCode on custom types ... 586

Section 103.4: Equals and GetHashCode in IEqualityComparator ... 587

Chapter 104: Type Conversion

... 589

Section 104.1: Explicit Type Conversion ... 589

(19)

Chapter 105: Parallel LINQ (PLINQ)

... 591

Section 105.1: Simple example ... 591

Section 105.2: WithDegreeOfParallelism ... 591

Section 105.3: AsOrdered ... 591

Section 105.4: AsUnordered ... 591

Chapter 106: String Manipulation

... 592

Section 106.1: Replacing a string within a string ... 592

Section 106.2: Finding a string within a string ... 592

Section 106.3: Removing (Trimming) white-space from a string ... 592

Section 106.4: Splitting a string using a delimiter ... 593

Section 106.5: Concatenate an array of strings into a single string ... 593

Section 106.6: String Concatenation ... 593

Section 106.7: Changing the case of characters within a String ... 593

Chapter 107: String Concatenate

... 595

Section 107.1: + Operator ... 595

Section 107.2: Concatenate strings using System.Text.StringBuilder ... 595

Section 107.3: Concat string array elements using String.Join ... 595

Section 107.4: Concatenation of two strings using $ ... 596

Chapter 108: Partial class and methods

... 597

Section 108.1: Partial classes ... 597

Section 108.2: Partial classes inheriting from a base class ... 597

Section 108.3: Partial methods ... 598

Chapter 109: Stopwatches

... 599

Section 109.1: IsHighResolution ... 599

Section 109.2: Creating an Instance of a Stopwatch ... 599

Chapter 110: Regex Parsing

... 601

Section 110.1: Single match ... 601

Section 110.2: Multiple matches ... 601

Chapter 111: C# Script

... 602

Section 111.1: Simple code evaluation ... 602

Chapter 112: Async/await, Backgroundworker, Task and Thread Examples

... 603

Section 112.1: ASP.NET Configure Await ... 603

Section 112.2: Task "run and forget" extension ... 605

Section 112.3: Async/await ... 605

Section 112.4: BackgroundWorker ... 606

Section 112.5: Task ... 607

Section 112.6: Thread ... 608

Chapter 113: Timers

... 609

Section 113.1: Multithreaded Timers ... 609

Section 113.2: Creating an Instance of a Timer ... 610

Section 113.3: Assigning the "Tick" event handler to a Timer ... 611

Section 113.4: Example: Using a Timer to perform a simple countdown ... 611

Chapter 114: Function with multiple return values

... 613

Section 114.1: "anonymous object" + "dynamic keyword" solution ... 613

Section 114.2: Tuple solution ... 613

Section 114.3: Ref and Out Parameters ... 613

Chapter 115: Binary Serialization

... 615

Section 115.1: Controlling serialization behavior with attributes ... 615

(20)

Section 115.3: Some gotchas in backward compatibility ... 617

Section 115.4: Making an object serializable ... 619

Section 115.5: Serialization surrogates (Implementing ISerializationSurrogate) ... 620

Section 115.6: Adding more control by implementing ISerializable ... 622

Chapter 116: Making a variable thread safe

... 624

Section 116.1: Controlling access to a variable in a Parallel.For loop ... 624

Chapter 117: IComparable

... 625

Section 117.1: Sort versions ... 625

Chapter 118: Code Contracts

... 627

Section 118.1: Postconditions ... 627

Section 118.2: Invariants ... 627

Section 118.3: Defining Contracts on Interface ... 628

Section 118.4: Preconditions ... 629

Chapter 119: Iterators

... 631

Section 119.1: Creating Iterators Using Yield ... 631

Section 119.2: Simple Numeric Iterator Example ... 632

Chapter 120: AssemblyInfo.cs Examples

... 633

Section 120.1: Global and local AssemblyInfo ... 633

Section 120.2: [AssemblyVersion] ... 633

Section 120.3: Automated versioning ... 634

Section 120.4: Common fields ... 634

Section 120.5: [AssemblyTitle] ... 634

Section 120.6: [AssemblyProduct] ... 634

Section 120.7: [InternalsVisibleTo] ... 634

Section 120.8: [AssemblyConfiguration] ... 635

Section 120.9: [AssemblyKeyFile] ... 635

Section 120.10: Reading Assembly Attributes ... 635

Chapter 121: File and Stream I/O

... 637

Section 121.1: Reading from a file using the System.IO.File class ... 637

Section 121.2: Lazily reading a file line-by-line via an IEnumerable ... 637

Section 121.3: Async write text to a file using StreamWriter ... 637

Section 121.4: Copy File ... 637

Section 121.5: Writing lines to a file using the System.IO.StreamWriter class ... 638

Section 121.6: Writing to a file using the System.IO.File class ... 638

Section 121.7: Create File ... 639

Section 121.8: Move File ... 639

Section 121.9: Delete File ... 640

Section 121.10: Files and Directories ... 640

Chapter 122: Code Contracts and Assertions

... 641

Section 122.1: Assertions to check logic should always be true ... 641

Chapter 123: Caching

... 642

Section 123.1: MemoryCache ... 642

Chapter 124: Implementing Flyweight Design Pattern

... 643

Section 124.1: Implementing map in RPG game ... 643

Chapter 125: StringBuilder

... 646

Section 125.1: What a StringBuilder is and when to use one ... 646

Section 125.2: Use StringBuilder to create string from a large number of records ... 647

Chapter 126: Implementing Decorator Design Pattern

... 648

(21)

Chapter 127: Accessing Databases

... 650

Section 127.1: Connection Strings ... 650

Section 127.2: Entity Framework Connections ... 650

Section 127.3: ADO.NET Connections ... 651

Chapter 128: T4 Code Generation

... 654

Section 128.1: Runtime Code Generation ... 654

Chapter 129: Microsoft.Exchange.WebServices

... 655

Section 129.1: Retrieve Specified User's Out of Oce Settings ... 655

Section 129.2: Update Specific User's Out of Oce Settings ... 655

Chapter 130: .NET Compiler Platform (Roslyn)

... 657

Section 130.1: Semantic model ... 657

Section 130.2: Syntax tree ... 657

Section 130.3: Create workspace from MSBuild project ... 658

Chapter 131: Data Annotation

... 659

Section 131.1: Data Annotation Basics ... 659

Section 131.2: Creating a custom validation attribute ... 659

Section 131.3: Manually Execute Validation Attributes ... 660

Section 131.4: Validation Attributes ... 660

Section 131.5: EditableAttribute (data modeling attribute) ... 661

Chapter 132: Using SQLite in C#

... 664

Section 132.1: Creating simple CRUD using SQLite in C# ... 664

Section 132.2: Executing Query ... 667

Chapter 133: System.Management.Automation

... 669

Section 133.1: Invoke simple synchronous pipeline ... 669

Chapter 134: FileSystemWatcher

... 670

Section 134.1: IsFileReady ... 670

Section 134.2: Basic FileWatcher ... 670

Chapter 135: System.DirectoryServices.Protocols.LdapConnection

... 672

Section 135.1: Authenticated SSL LDAP connection, SSL cert does not match reverse DNS ... 672

Section 135.2: Super Simple anonymous LDAP ... 673

Chapter 136: Named and Optional Arguments

... 674

Section 136.1: Optional Arguments ... 674

Section 136.2: Named Arguments ... 675

Chapter 137: Comments and regions

... 678

Section 137.1: Comments ... 678

Section 137.2: Regions ... 678

Section 137.3: Documentation comments ... 679

Chapter 138: C# Authentication handler

... 681

Section 138.1: Authentication handler ... 681

Chapter 139: Pointers & Unsafe Code

... 683

Section 139.1: Introduction to unsafe code ... 683

Section 139.2: Accessing Array Elements Using a Pointer ... 684

Section 139.3: Compiling Unsafe Code ... 684

Section 139.4: Retrieving the Data Value Using a Pointer ... 685

Section 139.5: Passing Pointers as Parameters to Methods ... 686

Chapter 140: Pointers

... 687

Section 140.1: Pointers for array access ... 687

(22)

Section 140.3: The asterisk is part of the type ... 688 Section 140.4: void* ... 688 Section 140.5: Member access using -> ... 688 Section 140.6: Generic pointers ... 689

Chapter 141: How to use C# Structs to create a Union type (Similar to C Unions)

... 690 Section 141.1: C-Style Unions in C# ... 690 Section 141.2: Union Types in C# can also contain Struct fields ... 691

Chapter 142: BigInteger

... 693 Section 142.1: Calculate the First 1,000-Digit Fibonacci Number ... 693

Chapter 143: Dependency Injection

... 694 Section 143.1: Dependency Injection C# and ASP.NET with Unity ... 694 Section 143.2: Dependency injection using MEF ... 696

Chapter 144: Reactive Extensions (Rx)

... 699 Section 144.1: Observing TextChanged event on a TextBox ... 699 Section 144.2: Streaming Data from Database with Observable ... 699

Chapter 145: Creational Design Patterns

... 700 Section 145.1: Singleton Pattern ... 700 Section 145.2: Factory Method pattern ... 701 Section 145.3: Abstract Factory Pattern ... 704 Section 145.4: Builder Pattern ... 706 Section 145.5: Prototype Pattern ... 710

Chapter 146: Creating a Console Application using a Plain-Text Editor and the C#

Compiler (csc.exe)

... 713 Section 146.1: Creating a Console application using a Plain-Text Editor and the C# Compiler ... 713

Chapter 147: Reading and writing .zip files

... 715 Section 147.1: Writing to a zip file ... 715 Section 147.2: Writing Zip Files in-memory ... 715 Section 147.3: Get files from a Zip file ... 715 Section 147.4: The following example shows how to open a zip archive and extract all .txt files to a folder

716 ...

Chapter 148: Lambda Expressions

... 717 Section 148.1: Using lambda syntax to create a closure ... 717 Section 148.2: Basic lambda expressions ... 717 Section 148.3: Basic lambda expressions with LINQ ... 718 Section 148.4: Lambda syntax with statement block body ... 718 Section 148.5: Lambda expressions with System.Linq.Expressions ... 718

Chapter 149: Generic Lambda Query Builder

... 719 Section 149.1: QueryFilter class ... 719 Section 149.2: GetExpression Method ... 719 Section 149.3: GetExpression Private overload ... 720 Section 149.4: ConstantExpression Method ... 721 Section 149.5: Usage ... 722

Chapter 150: Import Google Contacts

... 723 Section 150.1: Requirements ... 723 Section 150.2: Source code in the controller ... 723 Section 150.3: Source code in the view ... 726

Chapter 151: CLSCompliantAttribute

... 727 Section 151.1: Access Modifier to which CLS rules apply ... 727

(23)

Section 151.2: Violation of CLS rule: Unsigned types / sbyte ... 727 Section 151.3: Violation of CLS rule: Same naming ... 728 Section 151.4: Violation of CLS rule: Identifier _ ... 729 Section 151.5: Violation of CLS rule: Inherit from non CLSComplaint class ... 729

Chapter 152: ObservableCollection<T>

... 730 Section 152.1: Initialize ObservableCollection<T> ... 730

Chapter 153: Synchronization Context in Async-Await

... 731 Section 153.1: Pseudocode for async/await keywords ... 731 Section 153.2: Disabling synchronization context ... 731 Section 153.3: Why SynchronizationContext is so important? ... 732

Chapter 154: ICloneable

... 733 Section 154.1: Implementing ICloneable in a class ... 733 Section 154.2: Implementing ICloneable in a struct ... 733

Chapter 155: Read & Understand Stacktraces

... 735 Section 155.1: Stack trace for a simple NullReferenceException in Windows Forms ... 735

Chapter 156: Linq to Objects

... 737 Section 156.1: Using LINQ to Objects in C# ... 737

Chapter 157: ASP.NET Identity

... 741 Section 157.1: How to implement password reset token in asp.net identity using user manager ... 741

Chapter 158: Access network shared folder with username and password

... 744 Section 158.1: Code to access network shared file ... 744

Chapter 159: Asynchronous Socket

... 746 Section 159.1: Asynchronous Socket (Client / Server) example ... 746

Chapter 160: Structural Design Patterns

... 753 Section 160.1: Adapter Design Pattern ... 753

Chapter 161: O(n) Algorithm for circular rotation of an array

... 757 Section 161.1: Example of a generic method that rotates an array by a given shift ... 757

Chapter 162: Creating Own MessageBox in Windows Form Application

... 759 Section 162.1: How to use own created MessageBox control in another Windows Form application ... 759 Section 162.2: Creating Own MessageBox Control ... 759

Chapter 163: Including Font Resources

... 762 Section 163.1: Instantiate 'Fontfamily' from Resources ... 762 Section 163.2: Integration method ... 762 Section 163.3: Usage with a 'Button' ... 762

Chapter 164: Using json.net

... 764 Section 164.1: Using JsonConverter on simple values ... 764 Section 164.2: Collect all fields of JSON object ... 766

Chapter 165: Windows Communication Foundation

... 768 Section 165.1: Getting started sample ... 768

Credits

... 770

(24)

About

Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from:

http://GoalKicker.com/CSharpBook

This C# Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow.

Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright

of their respective owners unless otherwise specified

This is an unofficial free book created for educational purposes and is not affiliated with official C# group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective

company owners

The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk

(25)

Chapter 1: Getting started with C#

Language

Version Release Date 1.0 2002-01-01 1.22003-04-01 2.02005-09-01 3.02007-08-01 4.02010-04-01 5.02013-06-01 6.02015-07-01 7.02017-03-07

Section 1.1: Creating a new console application (Visual Studio)

Open Visual Studio

1.

In the toolbar, go to File → New Project 2.

Select the Console Application project type 3.

Open the file Program.cs in the Solution Explorer 4.

Add the following code to Main():

5.

public class Program

{

public static void Main()

{

// Prints a message to the console.

System.Console.WriteLine("Hello, World!");

/* Wait for the user to press a key. This is a common way to prevent the console window from terminating

and disappearing before the programmer can see the contents

of the window, when the application is run via Start from within VS. */ System.Console.ReadKey();

} }

In the toolbar, click Debug -> Start Debugging or hit F5 or ctrl + F5 (running without debugger) to run the 6.

program. Live Demo on ideone

Explanation

class Program is a class declaration. The class Program contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the Program class has only one method: Main.

static void Main() defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. Only one Main method is allowed per class.

System.Console.WriteLine("Hello, world!"); method prints a given data (in this example, Hello, world!) as an output in the console window.

System.Console.ReadKey(), ensures that the program won't close immediately after displaying the message.

(26)

the program. The program terminates when it has finished the last line of code in the main() method.

Using the command line

To compile via command line use either MSBuild or csc.exe (the C# compiler), both part of the Microsoft Build Tools package.

To compile this example, run the following command in the same directory where HelloWorld.cs is located: %WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe HelloWorld.cs

It can also be possible that you have two main methods inside one application. In this case, you have to tell the compiler which main method to execute by typing the following command in the console.(suppose Class ClassA also has a main method in the same HelloWorld.cs file in HelloWorld namespace)

%WINDIR%\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe HelloWorld.cs /main:HelloWorld.ClassA where HelloWorld is namespace

Note: This is the path where .NET framework v4.0 is located in general. Change the path according to your .NET version. In addition, the directory might be framework instead of framework64 if you're using the 32-bit .NET Framework. From the Windows Command Prompt, you can list all the csc.exe Framework paths by running the following commands (the first for 32-bit Frameworks):

dir %WINDIR%\\Microsoft.NET\\Framework\\csc.exe /s/b dir %WINDIR%\\Microsoft.NET\\Framework64\\csc.exe /s/b

There should now be an executable file named HelloWorld.exe in the same directory. To execute the program from the command prompt, simply type the executable's name and hit Enter as follows:

HelloWorld.exe This will produce:

(27)

You may also double click the executable and launch a new console window with the message "Hello, world!"

Section 1.2: Creating a new project in Visual Studio (console

application) and Running it in Debug mode

Download and install Visual Studio. Visual Studio can be downloaded from VisualStudio.com. The 1.

Community edition is suggested, first because it is free, and second because it involves all the general features and can be extended further.

Open Visual Studio. 2.

Welcome. Go to File → New → Project. 3.

Click Templates → Visual C# → Console Application 4.

(28)

After selecting Console Application, Enter a name for your project, and a location to save and press OK . 5.

Don't worry about the Solution name.

Project created. The newly created project will look similar to: 6.

(Always use descriptive names for projects so that they can easily be distinguished from other projects. It is recommended not to use spaces in project or class name.)

(29)

Write code. You can now update your Program.cs to present "Hello world!" to the user. 7.

using System;

namespace ConsoleApplication1

{

public class Program {

public static void Main(string[] args)

{

}

} }

Add the following two lines to the public static void Main(string[] args) object in Program.cs: (make sure it's inside the braces)

Console.WriteLine("Hello world!");

Console.Read();

Why Console.Read()? The first line prints out the text "Hello world!" to the console, and the second line

waits for a single character to be entered; in effect, this causes the program to pause execution so that you're able to see the output while debugging. Without Console.Read();, when you start debugging the application

it will just print "Hello world!" to the console and then immediately close. Your code window should now look like the following:

using System;

namespace ConsoleApplication1

{

public class Program {

public static void Main(string[] args)

{

Console.WriteLine("Hello world!");

Console.Read();

}

} }

Debug your program. Press the Start Button on the toolbar near the top of the window or press 8.

F5 on your keyboard to run your application. If the button is not present, you can run the program from the top menu: Debug → Start Debugging. The program will compile and then open a console window. It should look similar to the following screenshot:

(30)

Stop the program. To close the program, just press any key on your keyboard. The Console.Read() we

9.

added was for this same purpose. Another way to close the program is by going to the menu where the Start button was, and clicking on the Stop button.

Section 1.3: Creating a new program using .NET Core

First install the .NET Core SDK by going through the installation instructions for the platform of your choice: Windows

OSX Linux Docker

After the installation has completed, open a command prompt, or terminal window.

Create a new directory with mkdir hello_world and change into the newly created directory with cd

1.

hello_world.

Create a new console application with dotnet new console. 2.

This will produce two files: hello_world.csproj <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> </Project> Program.cs using System;

(31)

namespace hello_world

{

class Program {

static void Main(string[] args)

{

Console.WriteLine("Hello World!");

}

} }

Restore the needed packages with dotnet restore. 3.

Optional Build the application with dotnet build for Debug or dotnet build -c Release for Release. dotnet 4.

run will also run the compiler and throw build errors, if any are found. Run the application with dotnet run for Debug or dotnet run

5.

.\bin\Release\netcoreapp1.1\hello_world.dll for Release.

(32)

Section 1.4: Creating a new program using Mono

First install Mono by going through the install instructions for the platform of your choice as described in their installation section.

Mono is available for Mac OS X, Windows and Linux.

After installation is done, create a text file, name it HelloWorld.cs and copy the following content into it: public class Program

{

public static void Main()

{

System.Console.WriteLine("Hello, world!");

System.Console.WriteLine("Press any key to exit..");

System.Console.Read();

} }

If you are using Windows, run the Mono Command Prompt which is included in the Mono installation and ensures that the necessary environment variables are set. If on Mac or Linux, open a new terminal.

To compile the newly created file, run the following command in the directory containing HelloWorld.cs:

mcs -out:HelloWorld.exe HelloWorld.cs

The resulting HelloWorld.exe can then be executed with:

mono HelloWorld.exe

which will produce the output: Hello, world!

Press any key to exit..

Section 1.5: Creating a new query using LinqPad

LinqPad is a great tool that allows you to learn and test features of .Net languages (C#, F# and VB.Net.) Install LinqPad

1.

Create a new Query ( Ctrl + N ) 2.

(33)

Under language, select "C# statements" 3.

Type the following code and hit run ( F5 ) 4.

string hw = "Hello World";

(34)

You should see "Hello World" printed out in the results screen. 5.

Now that you have created your first .Net program, go and check out the samples included in LinqPad via the 6.

"Samples" browser. There are many great examples that will show you many different features of the .Net languages.

Notes:

If you click on "IL", you can inspect the IL code that your .net code generates. This is a great learning tool. 1.

(35)

When using LINQ to SQL or Linq to Entities you can inspect the SQL that's being generated which is 2.

another great way to learn about LINQ.

Section 1.6: Creating a new project using Xamarin Studio

Download and install Xamarin Studio Community.

1.

Open Xamarin Studio. 2.

Click File → New → Solution. 3.

(36)

Click .NET → Console Project and choose C#. 4.

Click Next to proceed. 5.

(37)

Enter the Project Name and Browse... for a Location to Save and then click Create . 6.

(38)

The newly created project will look similar to: 7.

This is the code in the Text Editor: 8.

References

Related documents

The traffic count previously carried out on New College Road clearly showed a level of traffic using this road link between London Road and Wenlock Road that was not attributable

Device address '&lt;address&gt;' contains a syntax error 16 Address '&lt;address&gt;' is out of range for the specified device or register 16 Data Type '&lt;type&gt;' is not valid

the disclosure of the source sanctioned in this provision is the prevention of criminal acts, similar with the second paragraph of Article 10 of the

When an envelope is sent to a fax recipient, DocuSign adds a fax cover sheet to the envelope and then faxes the envelope to the recipient’s fax number.. The recipient fills in

They provide an efficient way to store graph data and are popular back-end options for applications built using the KeyLines network visualization toolkit.. Storing connected data in

For two types T and U, if common_reference_t&lt;const remove_cvref_t&lt;T&gt;&amp;, const remove_cvref_t&lt;U&gt;&amp;&gt; is well-formed and denotes a type C such that

Can she declare a reference variable of excel array literal whose component type species an unbounded wildcard parameterized type.. Note the use of