Learn a simple tutorial to get started in c-sharp in X minutes
- 2020-04-01 03:07:57
- OfStack
// Single line comments // start
/// <summary>
/// XML document annotations
/// </summary>
//Declare the namespace used by the application
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using System.IO;
//Define scope and organize the code into packages
namespace Learning
{
//Each.cs file needs to contain at least one class with the same file name
//You may not do it, but it's not good.
public class LearnCSharp
{
//If you've used Java or C++ before, you can skip to "interesting features"
public static void Syntax()
{
//Print the message using console.writeline
Console.WriteLine("Hello World");
Console.WriteLine(
"Integer: " + 10 +
" Double: " + 3.14 +
" Boolean: " + true);
//Print using console.write without a newline symbol
Console.Write("Hello ");
Console.Write("World");
///////////////////////////////////////////////////
//Types and variables
//
//Use <Type> <Name> Define variables
///////////////////////////////////////////////////
//Sbyte - signed 8-bit integer
// (-128 <= sbyte <= 127)
sbyte fooSbyte = 100;
//Byte - unsigned 8-bit integer
// (0 <= byte <= 255)
byte fooByte = 100;
//Short 16-bit integer
//Signed - (-32,768 <= short <= 32767).
//Unsigned - (0 <= ushort <= 65535).
short fooShort = 10000;
ushort fooUshort = 10000;
//Integer - 32-bit Integer
int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
//Long - The 64 - bit integer
long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
//Number defaults to int or uint (depending on size)
//Use L to indicate that the variable value type is long or ulong
//Double - Double precision 64-bit IEEE 754 floating point number
double fooDouble = 123.4; //Accuracy: 15-16 bits
//Float - single precision 32-bit IEEE 754 floating point number
float fooFloat = 234.5f; //Precision: 7 bits
//Use f to indicate that the variable value type is float
//Decimal - 128-bits data type, more accurate than other floating point types, suitable for finance, finance
decimal fooDecimal = 150.3m;
//Boolean value -true & false
bool fooBoolean = true; //Or false
//Char - a single 16-bit Unicode character
char fooChar = 'A';
//Strings - unlike the previous basic type, Strings are not values, but references. This means that you can set the string to null.
string fooString = ""escape" quotes and add n (new lines) and t (tabs)";
Console.WriteLine(fooString);
//You can access each character of the string by index:
char charFromString = fooString[1]; // => 'e'
//String unmodifiable: fooString[1] = 'X' will not work.
//Compares strings based on current locale Settings, case insensitive
string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
//Sprintf-based string formatting
string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2);
//Date and format
DateTime fooDate = DateTime.Now;
Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
//Use the @ symbol to create a cross-line string. Use "" to denote"
string bazString = @"Here's some stuff
on a new line! ""Wow!"", the masses cried";
//Use const or readonly to define constants, which are evaluated at compile time
const int HOURS_I_WORK_PER_WEEK = 9001;
///////////////////////////////////////////////////
//The data structure
///////////////////////////////////////////////////
//Array - count from 0. When declaring an array, determine the length of the array.
//The format of the declaration array is as follows:
// <datatype>[] <var name> = new <datatype>[<array size>];
int[] intArray = new int[10];
//Other ways to declare and initialize arrays:
int[] y = { 9000, 1000, 1337 };
//Access the elements of the array
Console.WriteLine("intArray @ 0: " + intArray[0]);
//The array can be modified
intArray[1] = 1;
//The list of
//The list of More commonly used than arrays because lists are more flexible.
//The format of the declaration list is as follows:
// List<datatype> <var name> = new List<datatype>();
List<int> intList = new List<int>();
List<string> stringList = new List<string>();
List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize
//<> For generics - see below
//The list of There is no default value, and you must first add an element when accessing a list element
intList.Add(1);
Console.WriteLine("intList @ 0: " + intList[0]);
//Other data structures:
//Stack/queue
//Dictionaries (implementation of hash tables)
//Hash set
//A read-only collection
//Tuples (.net 4 +)
///////////////////////////////////////
//The operator
///////////////////////////////////////
Console.WriteLine("n->Operators");
int i1 = 1, i2 = 2; //Shorthand form for multiple declarations
//Straightforward arithmetic
Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
//Take more than
Console.WriteLine("11%3 = " + (11 % 3)); // => 2
//Comparison operator
Console.WriteLine("3 == 2? " + (3 == 2)); // => false
Console.WriteLine("3 != 2? " + (3 != 2)); // => true
Console.WriteLine("3 > 2? " + (3 > 2)); // => true
Console.WriteLine("3 < 2? " + (3 < 2)); // => false
Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
//An operator
//Self - increasing, self - decreasing
int i = 0;
Console.WriteLine("n->Inc/Dec-rementation");
Console.WriteLine(i++); //I = 1. Increase after the event
Console.WriteLine(++i); //I = 2. Self-increment in advance
Console.WriteLine(i--); //I = 1. Subtract after the fact
Console.WriteLine(--i); //I = 0. Self-subtract in advance
///////////////////////////////////////
//Control structure
///////////////////////////////////////
Console.WriteLine("n->Control Structures");
//An if statement similar to C
int j = 10;
if (j == 10)
{
Console.WriteLine("I get printed");
}
else if (j > 10)
{
Console.WriteLine("I don't");
}
else
{
Console.WriteLine("I also don't");
}
//Ternary expression
//The simple if/else statement can be written as:
// <condition> ? <true> : <false>
string isTrue = (true) ? "True" : "False";
//The While loop
int fooWhile = 0;
while (fooWhile < 100)
{
//Iterate 100 times, fooWhile 0-> 99
fooWhile++;
}
// DoThe While loop
int fooDoWhile = 0;
do
{
//Iterate 100 times, fooDoWhile 0-> 99
fooDoWhile++;
} while (fooDoWhile < 100);
//The for loop
//For loop => For (<Initial condition>; <Conditions>; <Step>)
for (int fooFor = 0; fooFor < 10; fooFor++)
{
//10 iterations, fooFor 0-> 9
}
//The foreach loop
//Foreach loop => Foreach (<Iterator type> <The iterator> In <Enumerable structure>)
//The foreach loop applies to any object that implements IEnumerable or IEnumerable.
// .Net The collection type under the frame ( An array of ,The list of, The dictionary ...) All implemented these interfaces.
//In the following code, ToCharArray() can be removed because the string also implements IEnumerable.
foreach (char character in "Hello World".ToCharArray())
{
//Iterates over all characters in the string
}
//A Switch statement
//The switch works for byte, short, char, and int data types.
//The same applies to enumerable types, including string classes,
//And some classes that encapsulate the original values: Character, Byte, Short, and Integer.
int month = 3;
string monthString;
switch (month)
{
case 1:
monthString = "January";
break;
case 2:
monthString = "February";
break;
case 3:
monthString = "March";
break;
//You can match multiple case statements at once
//But you need to use break after you add the case statement
//(otherwise you need to explicitly use the goto case x statement)
case 6:
case 7:
case 8:
monthString = "Summer time!!";
break;
default:
monthString = "Some other month";
break;
}
///////////////////////////////////////
//Convert the string to an integer. If the conversion fails, an exception will be thrown:
///////////////////////////////////////
// Converting data
//Convert the string to an integer. If the conversion fails, an exception will be thrown:
int.Parse("123");//Returns "123" of integer type
//TryParse tries to convert the type and returns the default type, such as 0, if it fails
int tryInt;
if (int.TryParse("123", out tryInt)) // Funciton is boolean
Console.WriteLine(tryInt); // 123
//Converts an integer to a string
//The Convert class provides a series of methods that facilitate conversion
Convert.ToString(123);
// or
tryInt.ToString();
}
///////////////////////////////////////
//class
///////////////////////////////////////
public static void Classes()
{
//See the object declaration at the end of the file
//Initialize the object with new
Bicycle trek = new Bicycle();
//Invoke the method of the object
trek.SpeedUp(3); //You should always use setter and getter methods
trek.Cadence = 100;
//View the object's information.
Console.WriteLine("trek info: " + trek.Info());
//Instantiate a new Penny Farthing
PennyFarthing funbike = new PennyFarthing(1, 10);
Console.WriteLine("funbike info: " + funbike.Info());
Console.Read();
} //End the main method
//Terminal programs terminal programs must have a main method as an entry
public static void Main(string[] args)
{
OtherInterestingFeatures();
}
//
//Interesting feature
//
//Default method signature
public //visibility
static //Allows you to call a class directly without creating an instance first
int //The return value
MethodSignatures(
int maxCount, //The first variable is of type integer
int count = 0, //If no value is passed in, the default value is 0
int another = 3,
params string[] otherParams //Capture other parameters
)
{
return -1;
}
//Methods can be renamed, as long as the signature is different
public static void MethodSignature(string maxCount)
{
}
//The generic
//The TKey and TValue classes are specified when the function is called with the user.
//The following function simulates Python's SetDefault
public static TValue SetDefault<TKey, TValue>(
IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultItem)
{
TValue result;
if (!dictionary.TryGetValue(key, out result))
return dictionary[key] = defaultItem;
return result;
}
//You can limit the range of incoming values
public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
{
//We can iterate because T is enumerable
foreach (var item in toPrint)
//Ittm as an integer
Console.WriteLine(item.ToString());
}
public static void OtherInterestingFeatures()
{
//Optional parameters
MethodSignatures(3, 1, 3, "Some", "Extra", "Strings");
MethodSignatures(3, another: 3); //Explicitly specify parameters, ignoring optional parameters
//Extension methods
int i = 3;
i.Print(); //See the definition below
//Nullable types are useful for database interactions and return values,
//Any value type (i.e. not a class) suffixed? It then becomes a null type
//<Type> ? <The variable name> = <Value>
int? nullable = null; //Nullable<Int> In short form
Console.WriteLine("Nullable variable: " + nullable);
bool hasValue = nullable.HasValue; //Returns true if not null
//?? Is the syntax sugar used to specify default values
//In case the variable is null
int notNullable = nullable ?? 0; // 0
//Variable type inference
//You can ask the compiler to infer variable types:
var magic = "magic is a string, at compile time, so you still get type safety";
// magic = 9; // Not working because magic It's a string, not an integer.
//The generic
//
var phonebook = new Dictionary<string, string>() {
{"Sarah", "212 555 5555"} //Add a new entry to the phone book
};
//Call SETDEFAULT, which is defined as generic above
Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); //No phone
//You don't have to specify TKey, TValue, because they are implicitly derived
Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555
//Lambda expressions - allow you to manipulate functions with a single line of code
Func<int, int> square = (x) => x * x; //The last term is the return value
Console.WriteLine(square(3)); // 9
//Disposable resource management - allows you to easily handle unmanaged resources. Most objects accessing unmanaged resources (file operators, device contexts, etc.) implement the IDisposable interface.
//The using statement cleans up IDisposable objects for you.
using (StreamWriter writer = new StreamWriter("log.txt"))
{
writer.WriteLine(" Nothing suspicious here ");
//At the end of the scope, the resource is recovered
//(even if an exception is thrown, it will be recovered)
}
//Parallel framework
// http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
var websites = new string[] {
"http://www.google.com", "http://www.reddit.com",
"http://www.shaunmccarthy.com"
};
var responses = new Dictionary<string, string>();
//Open a new thread for each request and merge the results before running the next step
Parallel.ForEach(websites,
new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads
website =>
{
// Do something that takes a long time on the file
using (var r = WebRequest.Create(new Uri(website)).GetResponse())
{
responses[website] = r.ContentType;
}
});
//The following code is not run until all requests are completed
foreach (var key in responses.Keys)
Console.WriteLine("{0}:{1}", key, responses[key]);
//Dynamic objects (easy to use with other languages)
dynamic student = new ExpandoObject();
student.FirstName = "First Name"; //No need to define the class first!
//You can even add methods (accept a string, output a string)
student.Introduce = new Func<string, string>(
(introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo));
Console.WriteLine(student.Introduce("Beth"));
//IQUERYABLE<T> - almost all collections implement it, bringing you Map/Filter/Reduce style methods
var bikes = new List<Bicycle>();
bikes.Sort(); // Sorts the array
bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); //Sort by the number of wheels
var result = bikes
.Where(b => b.Wheels > 3) //Filter - can be chained (return queryable)
.Where(b => b.IsBroken && b.HasTassles)
.Select(b => b.ToString()); //Map - here we use select, so the result is queryable<The string
var sum = bikes.Sum(b => b.Wheels); //Reduce - calculates the total number of wheels in the set
//Creates a list of implicit objects that are generated based on some parameters of the bicycle
var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
//It's hard to demonstrate, but the compiler can deduce the type of the above object before the code is compiled
foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
Console.WriteLine(bikeSummary.Name);
// ASPARALLEL
//Evil feature - a combination of linq and parallel operations
var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
//The above code runs concurrently. New threads are automatically opened to calculate the results separately. It is suitable for multi-core and large data scenarios.
//LINQ - will IQueryable<T> Map to storage, defer execution, such as LinqToSql mapping database, LinqToXml mapping XML documents.
var db = new BikeRespository();
//Execution was delayed, which is good for querying the database
var filter = db.Bikes.Where(b => b.HasTassles); //Do not run the query
if (42 > 6) //You can continually add filters, including conditional filters, such as for the "advanced search" feature
filter = filter.Where(b => b.IsBroken); //Do not run the query
var query = filter
.OrderBy(b => b.Wheels)
.ThenBy(b => b.Name)
.Select(b => b.Name); //The query is still not running
//Now run the query, and when you run the query, you open a reader, so you iterate over a copy
foreach (string bike in query)
Console.WriteLine(result);
}
} //End LearnCSharp class
//You can include other classes in the same.cs file
public static class Extensions
{
//Extension function
public static void Print(this object obj)
{
Console.WriteLine(obj.ToString());
}
}
//Syntax for declaration classes:
//<Public/private/protected/internal> The class <The name of the class> {
// // The data fields , The constructor , Internal function .
/ //In Java functions are called methods.
// }
public class Bicycle
{
//Bike fields, variables
public int Cadence //Public: anywhere
{
get //Get - defines a method to get a property
{
return _cadence;
}
set //Set - defines a method for setting properties
{
_cadence = value; //Value is the value that is passed to the setter
}
}
private int _cadence;
protected virtual int Gear //Classes and subclasses can be accessed
{
get; //Create an automatic property that does not require a member field
set;
}
internal int Wheels //Internal: accessible within the same assembly
{
get;
private set; //You can add modifiers to the get/set method
}
int _speed; //The default is private: only accessible within this class, you can also use the 'private' keyword
public string Name { get; set; }
//The enum type contains a set of constants that map names to values (an integer unless otherwise specified).
//Enmu element types can be a byte, sbyte, short, ushort, int, uint, long, ulong. Enum cannot contain the same value.
public enum BikeBrand
{
AIST,
BMC,
Electra = 42, //You can explicitly assign values
Gitane // 43
}
//We defined this type in the Bicycle class, so it's an inline type. Code outside of this class should be referenced using bicycle.brand.
public BikeBrand Brand; //After declaring an enum type, we can declare fields of that type
//A static method
//A static method Type is itself and does not belong to a particular object. You can access objects without reference to them.
static public int BicyclesCreated = 0;
//A read-only value
//A read-only value At run time, they can only be assigned in a declaration or constructor.
readonly bool _hasCardsInSpokes = false; // read-only private
//Constructors are a way to create classes.
//The following is a default constructor.
public Bicycle()
{
this.Gear = 1; //You can use the keyword this to access the members of the object
Cadence = 50; //But you don't always need it
_speed = 5;
Name = "Bontrager";
Brand = BikeBrand.AIST;
BicyclesCreated++;
}
//Another example of a constructor (with parameters)
public Bicycle(int startCadence, int startSpeed, int startGear,
string name, bool hasCardsInSpokes, BikeBrand brand)
: base() //So let's call base
{
Gear = startGear;
Cadence = startCadence;
_speed = startSpeed;
Name = name;
_hasCardsInSpokes = hasCardsInSpokes;
Brand = brand;
}
//Constructors can be interlocked
public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
this(startCadence, startSpeed, 0, "big wheels", true, brand)
{
}
//Function syntax:
//<Public/private/protected> <The return value> <Function name> (<Parameter>)
//Classes can implement getters and setters methods for their fields for fields, or they can implement properties (C# recommends this).
//Method arguments can have default values. If there is a default value, you can omit the corresponding parameter when calling a method.
public void SpeedUp(int increment = 1)
{
_speed += increment;
}
public void SlowDown(int decrement = 1)
{
_speed -= decrement;
}
//Properties can access and set values. Consider using attributes when you only need to access data. Properties can define get and set, or both.
private bool _hasTassles; // private variable
public bool HasTassles // public accessor
{
get { return _hasTassles; }
set { _hasTassles = value; }
}
//You can define an auto property in one line, and this syntax will automatically create a backup field. You can set access modifiers for getters or setters to restrict their access.
public bool IsBroken { get; private set; }
//The implementation of the property can be automatic
public int FrameSize
{
get;
//You can specify access modifiers for get or set
//The following code means that only the Bicycle class can call the set of Framesize
private set;
}
//Method to display the properties of an object
public virtual string Info()
{
return "Gear: " + Gear +
" Cadence: " + Cadence +
" Speed: " + _speed +
" Name: " + Name +
" Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") +
"n------------------------------n"
}
//Methods can be static. Usually used as an auxiliary method.
public static bool DidWeCreateEnoughBycles()
{
//In static methods, you can only refer to static members of a class
return BicyclesCreated > 9000;
} //If your class only needs static members, consider treating the entire class as a static class.
} //End of the Bicycle class
//PennyFarthing is a subclass of Bicycle
class PennyFarthing : Bicycle
{
//Penny Farthings are bicycles with large front wheels. No gear.)
//Invoke the parent constructor
public PennyFarthing(int startCadence, int startSpeed) :
base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra)
{
}
protected override int Gear
{
get
{
return 0;
}
set
{
throw new ArgumentException(" You can't be here PennyFarthing Upper switching gear ");
}
}
public override string Info()
{
string result = "PennyFarthing bicycle ";
result += base.ToString(); //Calling the parent method
return result;
}
}
//The interface contains only the signature of the member, not the implementation.
interface IJumpable
{
void Jump(int meters); //All interface members are implicitly exposed
}
interface IBreakable
{
bool Broken { get; } //Interfaces can contain properties, methods, and events
}
//Classes can inherit from only one class, but you can implement any number of interfaces
class MountainBike : Bicycle, IJumpable, IBreakable
{
int damage = 0;
public void Jump(int meters)
{
damage += meters;
}
public bool Broken
{
get
{
return damage > 100;
}
}
}
/// <summary>
//Connect to a database, an example of LinqToSql. EntityFramework Code First is great (Ruby like ActiveRecord, but bidirectional)
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
/// </summary>
public class BikeRespository : DbSet
{
public BikeRespository()
: base()
{
}
public DbSet<Bicycle> Bikes { get; set; }
}
} // The end of the Namespace
Note that topics not covered are:
1. The Flags
2. The Attributes
3. Static properties
4. Exceptions, Abstraction
6. asp.net (Web Forms/MVC/WebMatrix)
6. Winforms
7. Windows Presentation Foundation (WPF)