summaryrefslogtreecommitdiffhomepage
path: root/csharp.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'csharp.html.markdown')
-rw-r--r--csharp.html.markdown161
1 files changed, 95 insertions, 66 deletions
diff --git a/csharp.html.markdown b/csharp.html.markdown
index df6544d3..1d7d0881 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -1,5 +1,5 @@
---
-language: c#
+language: C#
contributors:
- ["Irfan Charania", "https://github.com/irfancharania"]
- ["Max Yankov", "https://github.com/golergka"]
@@ -12,22 +12,24 @@ contributors:
filename: LearnCSharp.cs
---
-C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework.
+C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the cross-platform .NET framework.
-[Read more here.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx)
+[Read more here.](https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/)
```c#
// Single-line comments start with //
+
/*
Multi-line comments look like this
*/
+
/// <summary>
/// This is an XML documentation comment which can be used to generate external
/// documentation or provide context help within an IDE
/// </summary>
/// <param name="firstParam">This is some parameter documentation for firstParam</param>
/// <returns>Information on the returned value of a function</returns>
-//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {}
+public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { }
// Specify the namespaces this source code will be using
// The namespaces below are all part of the standard .NET Framework Class Library
@@ -46,6 +48,10 @@ using System.Data.Entity;
// Namespaces define scope to organize code into "packages" or "modules"
// Using this code from another source file: using Learning.CSharp;
+
+// You can also do this in C# 10, it is called file-scoped namespaces.
+// namespace Learning.CSharp;
+
namespace Learning.CSharp
{
// Each .cs file should at least contain a class with the same name as the file.
@@ -152,7 +158,7 @@ on a new line! ""Wow!"", the masses cried";
// Arrays - zero indexed
// The array size must be decided upon declaration
- // The format for declaring an array is follows:
+ // The format for declaring an array is
// <datatype>[] <var name> = new <datatype>[<array size>];
int[] intArray = new int[10];
@@ -166,7 +172,7 @@ on a new line! ""Wow!"", the masses cried";
// Lists
// Lists are used more frequently than arrays as they are more flexible
- // The format for declaring a list is follows:
+ // The format for declaring a list is
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
@@ -176,14 +182,14 @@ on a new line! ""Wow!"", the masses cried";
// Lists don't default to a value;
// A value must be added before accessing the index
intList.Add(1);
- Console.WriteLine("intList @ 0: " + intList[0]);
+ Console.WriteLine("intList at 0: " + intList[0]);
- // Others data structures to check out:
+ // Other data structures to check out:
// Stack/Queue
// Dictionary (an implementation of a hash map)
// HashSet
// Read-only Collections
- // Tuple (.Net 4+)
+ // Tuple (.NET 4+)
///////////////////////////////////////
// Operators
@@ -216,20 +222,20 @@ on a new line! ""Wow!"", the masses cried";
| Bitwise inclusive OR
*/
- // Incrementations
+ // Incrementing
int i = 0;
- Console.WriteLine("\n->Inc/Dec-rementation");
- Console.WriteLine(i++); //Prints "0", i = 1. Post-Incrementation
- Console.WriteLine(++i); //Prints "2", i = 2. Pre-Incrementation
- Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrementation
- Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrementation
+ Console.WriteLine("\n->Inc/Dec-rement");
+ Console.WriteLine(i++); //Prints "0", i = 1. Post-Increment
+ Console.WriteLine(++i); //Prints "2", i = 2. Pre-Increment
+ Console.WriteLine(i--); //Prints "2", i = 1. Post-Decrement
+ Console.WriteLine(--i); //Prints "0", i = 0. Pre-Decrement
///////////////////////////////////////
// Control Structures
///////////////////////////////////////
Console.WriteLine("\n->Control Structures");
- // If statements are c-like
+ // If statements are C-like
int j = 10;
if (j == 10)
{
@@ -254,7 +260,7 @@ on a new line! ""Wow!"", the masses cried";
int fooWhile = 0;
while (fooWhile < 100)
{
- //Iterated 100 times, fooWhile 0->99
+ // Iterated 100 times, fooWhile 0->99
fooWhile++;
}
@@ -273,25 +279,25 @@ on a new line! ""Wow!"", the masses cried";
} while (fooDoWhile < 100);
- //for loop structure => for(<start_statement>; <conditional>; <step>)
+ // for loop structure => for(<start_statement>; <conditional>; <step>)
for (int fooFor = 0; fooFor < 10; fooFor++)
{
- //Iterated 10 times, fooFor 0->9
+ // Iterated 10 times, fooFor 0->9
}
// For Each Loop
// foreach loop structure => foreach(<iteratorType> <iteratorName> in <enumerable>)
// The foreach loop loops over any object implementing IEnumerable or IEnumerable<T>
- // All the collection types (Array, List, Dictionary...) in the .Net framework
+ // All the collection types (Array, List, Dictionary...) in the .NET framework
// implement one or both of these interfaces.
// (The ToCharArray() could be removed, because a string also implements IEnumerable)
foreach (char character in "Hello World".ToCharArray())
{
- //Iterated over all the characters in the string
+ // Iterated over all the characters in the string
}
// Switch Case
- // A switch works with the byte, short, char, and int data types.
+ // A switch works with byte, short, char, and int data types.
// It also works with enumerated types (discussed in Enum Types),
// the String class, and a few special classes that wrap
// primitive types: Character, Byte, Short, and Integer.
@@ -310,7 +316,7 @@ on a new line! ""Wow!"", the masses cried";
break;
// You can assign more than one case to an action
// But you can't add an action without a break before another case
- // (if you want to do this, you would have to explicitly add a goto case x
+ // (if you want to do this, you would have to explicitly add a goto case x)
case 6:
case 7:
case 8:
@@ -329,18 +335,27 @@ on a new line! ""Wow!"", the masses cried";
// Convert String To Integer
// this will throw a FormatException on failure
- int.Parse("123");//returns an integer version of "123"
+ int.Parse("123"); // returns an integer version of "123"
- // try parse will default to type default on failure
- // in this case: 0
+ // TryParse will default to the type's default value on failure
+ // in this case 0
int tryInt;
if (int.TryParse("123", out tryInt)) // Function is boolean
Console.WriteLine(tryInt); // 123
// Convert Integer To String
- // Convert class has a number of methods to facilitate conversions
+ // The Convert class has a number of methods to facilitate conversions
+
+ // String to int
+
+ // Better
+ bool result = int.TryParse(string, out var integer)
+ int.Parse(string);
+
+ // Not recommended
Convert.ToString(123);
- // or
+
+ // Int to string
tryInt.ToString();
// Casting
@@ -373,7 +388,10 @@ on a new line! ""Wow!"", the masses cried";
Console.Read();
} // End main method
- // CONSOLE ENTRY A console application must have a main method as an entry point
+ // Available in C# 9 and later, this is basically syntactic sugar for a class. Records are immutable*.
+ public record ARecord(string Csharp);
+
+ // CONSOLE ENTRY - A console application must have a main method as an entry point
public static void Main(string[] args)
{
OtherInterestingFeatures();
@@ -404,13 +422,13 @@ on a new line! ""Wow!"", the masses cried";
ref int maxCount, // Pass by reference
out int count)
{
- //the argument passed in as 'count' will hold the value of 15 outside of this function
+ // the argument passed in as 'count' will hold the value of 15 outside of this function
count = 15; // out param must be assigned before control leaves the method
}
// GENERICS
// The classes for TKey and TValue is specified by the user calling this function.
- // This method emulates the SetDefault of Python
+ // This method emulates Python's dict.setdefault()
public static TValue SetDefault<TKey, TValue>(
IDictionary<TKey, TValue> dictionary,
TKey key,
@@ -552,7 +570,7 @@ on a new line! ""Wow!"", the masses cried";
}
// PARALLEL FRAMEWORK
- // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
+ // https://devblogs.microsoft.com/csharpfaq/parallel-programming-in-net-framework-4-getting-started/
var words = new List<string> {"dog", "cat", "horse", "pony"};
@@ -564,11 +582,11 @@ on a new line! ""Wow!"", the masses cried";
}
);
- //Running this will produce different outputs
- //since each thread finishes at different times.
- //Some example outputs are:
- //cat dog horse pony
- //dog horse pony cat
+ // Running this will produce different outputs
+ // since each thread finishes at different times.
+ // Some example outputs are:
+ // cat dog horse pony
+ // dog horse pony cat
// DYNAMIC OBJECTS (great for working with other languages)
dynamic student = new ExpandoObject();
@@ -651,10 +669,10 @@ on a new line! ""Wow!"", the masses cried";
return ++count;
}
- // A delegate is a reference to a method
+ // A delegate is a reference to a method.
// To reference the Increment method,
- // first declare a delegate with the same signature
- // ie. takes no arguments and returns an int
+ // first declare a delegate with the same signature,
+ // i.e. takes no arguments and returns an int
public delegate int IncrementDelegate();
// An event can also be used to trigger delegates
@@ -725,10 +743,10 @@ on a new line! ""Wow!"", the masses cried";
int _speed; // Everything is private by default: Only accessible from within this class.
// can also use keyword private
public string Name { get; set; }
-
+
// Properties also have a special syntax for when you want a readonly property
// that simply returns the result of an expression
- public string LongName => Name + " " + _speed + " speed";
+ public string LongName => Name + " " + _speed + " speed";
// Enum is a value type that consists of a set of named constants
// It is really just mapping a name to a value (an int, unless specified otherwise).
@@ -742,7 +760,7 @@ on a new line! ""Wow!"", the masses cried";
Gitane // 43
}
// We defined this type inside a Bicycle class, so it is a nested type
- // Code outside of this class should reference this type as Bicycle.Brand
+ // Code outside of this class should reference this type as Bicycle.BikeBrand
public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type
@@ -865,7 +883,7 @@ on a new line! ""Wow!"", the masses cried";
}
}
- //Method to display the attribute values of this Object.
+ // Method to display the attribute values of this Object.
public virtual string Info()
{
return "Gear: " + Gear +
@@ -960,7 +978,7 @@ on a new line! ""Wow!"", the masses cried";
/// <summary>
/// Used to connect to DB for LinqToSql example.
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
- /// http://msdn.microsoft.com/en-us/data/jj193542.aspx
+ /// https://docs.microsoft.com/ef/ef6/modeling/code-first/workflows/new-database
/// </summary>
public class BikeRepository : DbContext
{
@@ -1069,7 +1087,7 @@ on a new line! ""Wow!"", the masses cried";
{
private static bool LogException(Exception ex)
{
- /* log exception somewhere */
+ // log exception somewhere
return false;
}
@@ -1089,7 +1107,7 @@ on a new line! ""Wow!"", the masses cried";
// Spell failed
return false;
}
- // Other exceptions, or MagicServiceException where Code is not 42
+ // Other exceptions, or MagicServiceException where Code is not 42
catch(Exception ex) when (LogException(ex))
{
// Execution never reaches this block
@@ -1117,12 +1135,12 @@ on a new line! ""Wow!"", the masses cried";
[Obsolete("Use NewMethod instead", false)]
public static void ObsoleteMethod()
{
- /* obsolete code */
+ // obsolete code
}
public static void NewMethod()
{
- /* new code */
+ // new code
}
public static void Main()
@@ -1154,9 +1172,9 @@ namespace Learning.More.CSharp
}
}
-//New C# 7 Feature
-//Install Microsoft.Net.Compilers Latest from Nuget
-//Install System.ValueTuple Latest from Nuget
+// New C# 7 Feature
+// Install Microsoft.Net.Compilers Latest from Nuget
+// Install System.ValueTuple Latest from Nuget
using System;
namespace Csharp7
{
@@ -1213,7 +1231,7 @@ namespace Csharp7
Console.WriteLine(tt.GetLastName());
}
}
-
+
// PATTERN MATCHING
class PatternMatchingTest
{
@@ -1297,26 +1315,37 @@ namespace Csharp7
```
## Topics Not Covered
+✨ New, 👍 Old, 🎈 LTS, 🔥 Cross-platform, 🎁 Windows-only
* Attributes
- * async/await
+
+ * Asynchronous Programming
+
* Web Development
- * ASP.NET MVC & WebApi (new)
- * ASP.NET Web Forms (old)
- * WebMatrix (tool)
+ * ASP.NET Core ✨
+
* Desktop Development
- * Windows Presentation Foundation (WPF) (new)
- * Winforms (old)
+ * Windows Presentation Foundation 👍 🎈 🎁
+ * Universal Windows Platform ✨ 🎁
+ * Uno Platform 🔥 ✨
+ * WinForms 👍 🎈 🎁
+ * Avalonia 🔥 ✨
+ * WinUI ✨ 🎁
+
+* Cross-platform Development
+ * Xamarin.Forms 👍
+ * MAUI ✨
+
## Further Reading
+ * [C# language reference](https://docs.microsoft.com/dotnet/csharp/language-reference/)
+ * [Learn .NET](https://dotnet.microsoft.com/learn)
+ * [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions)
* [DotNetPerls](http://www.dotnetperls.com)
* [C# in Depth](http://manning.com/skeet2)
- * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
- * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
- * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
- * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
- * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Programming C# 5.0](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
- * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx)
+ * [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8)
+