static void Main(string[] args) { int num1 = 5; Console.WriteLine("Hello"); Console.Write("Hello"); Console.WriteLine("num1: " + num1); Console.ReadLine(); }
Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.WriteLine("Hello " + name);
int num = Conver.ToInt32("45");
Console.Write("Enter a number: "); // enter 3.5 double num = Conver.ToDouble(Console.ReadLine()); Console.WriteLine(num);
string phrase = "Hello World"; string color, name;
char grade = 'A'; bool result = char.IsLetter(grade);
sbyte x = 120;
short x = 30000;
int age = 30; int num; // default value is 0;
int num = 6; num++; num--;
long x = 5;
float f = 3_000.5F; f = 5.4f;
double d = 3D; d = 4d; d = 3.1415;
decimal - high level of accuracy decimal myMoney = 3_000.5m; myMoney = 400.75M;
Console.WriteLine(5 + 8.1); // result 13.1 - decimal Console.WriteLine(5 / 2); // result is 2 because of math operation with integer numbers Console.WriteLine(5 / 2.0); // result is 2.5 because one operand is a double
bool isMail = false; bool isMail = true;
const double PI = 3.14159265359; const int weeks = 52, months = 12;
int num = 123; long bigNum = num; float myFloat = 13.37F; double myDouble = myFloat;
double myDouble = 13.78; int myInt; myInt = (int)myDouble; Console.WriteLine(myInt); // output is 13
string myStr = myDouble.ToString()
bool isMale = true; string myStr = isMale.ToString(); // "true"
string phrase = "Hello \"World";
string phrase = "Hello " + "World";
phrase.Length phrase.ToUpper() phrase.ToLower() phrase.Contains("World") // True or False phrase[0] // First character phrase.IndexOf("World") // starts at index position phrase.IndexOf('o') phrase.IndexOf('z') // -1 phrase.Substring(4) // sub string from position 4 phrase.Substring(4,3) // sub string from position 4, 3 characters to take phrase.IsNullOrWhiteSpace // returns true if the string is either null or blank, else returns false string fullName = string.Concat(str1, " ", str2); String.Format("My name is {0}, name"); // output: my name is John string inputValue = string.Empty;
string secretWord = "giraffe"; string guess = ""; while (guess != secretWord) { Console.Write("Enter guess: "); guess = Console.ReadLine(); } Console.Write("You Win!");
int age = 25; string name = "John"; Console.WriteLine($"Hello, my name is {name} and I am {age} years old.");Output:
Hello, my name is John and I am 25 years old.
Console.WriteLine(@"C:\Users\user1\Desktop\");
Output: C:\Users\user1\Desktop\
Console.WriteLine(@"Lorem ipsum dolor sit \n amet, consectetur adipisicing elit. Tempora, nihil!");Output:
Lorem ipsum dolor sit \n amet, consectetur adipisicing elit. Tempora, nihil!
int age = 20; string name = "John"; Console.WriteLine("Hello, my name is {0} and I am {1} years old.", name, age);Output:
Hello, my name is John and I am 20 years old.
string myStr = "100"; int num = int.Parse(myStr); OR int num = Int32.Parse(myStr); Console.WriteLine(num); // output is 100
string numberAsString = "120"; int parsedValue; bool success = int.TryParse(numberAsString, out parsedValue); if (success) { Console.WriteLine($"Parsing successful, the number is {parsedValue}"); } else { Console.WriteLine("Parsing has failed"); }
string numberAsString = "0.85"; float num1 = float.Parse(numberAsString); Console.WriteLine("num1: {0} ", num1);
string numberAsString = "0.33"; // good for float float parsedValue; bool success = float.TryParse(numberAsString, out parsedValue); if (success) { Console.WriteLine($"Parsing successful, the number is {parsedValue}"); } else { Console.WriteLine("Parsing has failed"); }
Math.Round(8.3) // 8 Math.Round(4.6) // 5 Math.Abs(-40) // 40 Math.Pow(3, 2) // 9 Math.Sqrt(36) // 6 Math.Max(4, 90) // 90 Math.Min(4, 90) // 4
static void Main(string[] args) { SayHi(); Console.ReadLine(); } static void SayHi() { Console.WriteLine("Hello User"); }
static void Main(string[] args) { SayHi("John"); Console.ReadLine(); } static void SayHi(string name) { Console.WriteLine("Hello " + name); }
static void Main(string[] args) { Console.WriteLine(cube(5)); // OR int cubedNumber = cube(5); Console.WriteLine(cubedNumber); Console.ReadLine(); } static int cube(int num) { int result = num * num * num; return result; }
params
params
keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.
int minimum = MinV2(10, 15, 1, 2, 3, -8, 20); // here we pass 7 values Console.WriteLine($"Minimum is {minimum}"); ... static int MinV2(params int[] numbers) { int min = int.MaxValue; foreach (int num in numbers) { if (num < min) { min = num; } } return min; }
bool isMale = true; if (isMale) { Console.WriteLine("You are male"); } else { Console.WriteLine("You are not male"); }
bool isMale = true; bool isTall = true; if (isMale && isTall) // and { Console.WriteLine("You are a tall male"); } else { Console.WriteLine("You are either not male or not tall or both"); }
if (isMale || isTall) // or
if (isMale && isTall) { Console.WriteLine("You are a tall male"); } else if (isMale && !isTall) // ! - not { ... } else if (!isMale && isTall) { ... } else { }
static int GetMax(int num1, num2) { int result; if (num1 > num2) { result = num1; } else { result = num2; } return result; }
if (num1 > num2) { } else if (num1 == num2) { } else { }
bool isEven = 6 % 2 == 0 ? true : false;
static string GetDay(int dayNum) { string dayName; switch (dayName) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; default: dayName = "Invalid Day Number" } return dayName; }
&& ||
> >= < <= == !=
bool isLower; isLower = num1 < num2; // False
bool isEqual; isEqual = num1 == num2; // True
bool isSunny = true; bool res = !isSunny;
int num1 = 5; int num2 = -num1; // same as -1*num1
int num = 0; num++; // takes effect on the next line ++num; // takes effect on the current line
int num = 0; num--; // takes effect on the next line --num; // takes effect on the current line
+ - * <-- multiplication / <-- division % < modulo operator - the remainder of the division
int index = 1; while (index <= 5 ) { Console.WriteLine(index); index++; }
int index = 1; do { Console.WriteLine(index); index++; } while (index <= 5 )
for(int i = 1; i <= 10; i++) { }
int[] nums = { 10, 20, 30, 40, 50 }; foreach(int num in nums) { Console.WriteLine(num); // here num cannot be changed }
static bool isAlphabetic(string str) { foreach(char c in str) { if (! char.IsLetter(c)) { return false; } } return true; }
int[] numbers = new int[3];OR
int[] numbers = new int[] {1, 2, 3, 4, 5};OR
int[] numbers = new int[3] {1, 2, 3};OR
int[] numbers = {1, 2, 3};OR
int[,] array2D = { {1,2}, {3,4} };
int[] numbers = {1, 2, 3}; numbers.Length;
int dimensions = array2D.Rank;
int[] luckyNumbers = { 4, 8, 15, 16, 23, 42}; Console.WriteLine(luckyNumbers[0]); luckyNumbers[1] = 900;
for (int i = 0; i < luckyNumbers.Length; i++) { Console.WriteLine([i]); }
string[] friends = new string[5]; // 5 is a size of the array friends[0] = "Jim"; friends[1] = "John";
int[,] numberGrid = { { 1, 2 }, // element at x position 0 { 3, 4 }, { 5, 6 } }; Console.WriteLine(numberGrid[0, 0]); // row 0, column 0 is 1 Console.WriteLine(numberGrid[1, 1]); // row 1, column 1 is 4
int[,] myArray = new int[2, 3]; // 2 rows, 3 columns
string[,] matrix;
int[,] matrix = { {1,2,3}, {4,5,6}, {7,8,9}, } matrix.GetLength(0) // get number of rows matrix.GetLength(1) // get number of columns
int[,] matrix = { {1,2,3}, {4,5,6}, {7,8,9}, }; foreach (int num in matrix) { Console.Write(num + " "); // output: 1 2 3 4 5 6 7 8 9 // here num cannot be changed } for (int i = 0, j = matrix.GetLength(0) - 1; i < matrix.GetLength(0); i++, j--) { Console.Write(matrix[i, j] + " "); // output: 3 5 7 }
for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { Console.Write(matrix[i, j] + " "); } Console.WriteLine(); } output: 1 2 3 4 5 6 7 8 9
int[,,] numberGrid = { { 1, 2, 7 }, // element at x position 0 { 3, 4, 8 }, { 5, 6, 9 } };
int[,,] threeD;
int[][] jaggedArray = new int[3][]; // three arrays within this jaggedArray jaggedArray[0] = new int[5]; jaggedArray[1] = new int[3]; jaggedArray[2] = new int[2];
int[][] jaggedArray = new int[3][]; // three arrays within this jaggedArray jaggedArray[0] = new int[] { 2, 3, 5, 7, 11 }; jaggedArray[1] = new int[] { 1, 2, 3 }; jaggedArray[2] = new int[] { 13, 21 };
int[][] jaggedArray2 = new int[][] { new int[] { 2, 3, 5, 7, 11 }, new int[] { 1, 2, 3 }, new int[] { 13, 21 } };
Console.WriteLine("The value in the middle of the first entry is {0}", jaggedArray2[0][2]);
foreach (int[] item in jaggedArray2) { foreach (int num in item) { Console.Write(num + " "); } Console.WriteLine(); }
for (int i = 0; i < jaggedArray2.Length; i++) { for (int j = 0; j < jaggedArray2[i].Length; j++) { Console.Write(jaggedArray2[i][j] + " "); } Console.WriteLine(); }
List<int> numbers = new List<int>();OR
List<int> numbers = new List<int> {1, 2, 3};OR
var numbers = new List<int>();OR
var numbers = new List<int>{1, 5, 35, 100};
Console.WriteLine(string.Join(", ", months));
var numbers = new List<int>(); numbers.Add(7);
numbers.Remove(7); int index = 0; numbers.RemoveAt(index); // Remove an element at specific index
var numbers = new List<int>(); numbers.Add(7); int value = numbers[0]; // Will be 7
var numbers = new List<int>(); numbers.Add(7); numbers.Clear(); // Deletes every element in our list
var numbers = new List<int>{1, 5, 35, 100};
foreach(int element in numbers) { Console.Write(element); }
for (int i = 0; i < numbers.Count; i++) { Console.Write(element); }
public static List<string>GetFriends(List<string> list) { var buffer = new List<string>(list); }
using System.Collections;
ArrayList myArrayList = new ArrayList(); OR ArrayList myArrayList = new ArrayList(100); // Will contain 100 objects
ArrayList myArrayList = new ArrayList(); myArrayList.Add(25); myArrayList.Add("Hello"); myArrayList.Add(13.37); myArrayList.Add(13); myArrayList.Add(128); myArrayList.Add(25.3); myArrayList.Add(13); myArrayList.Remove(13); // Delete the first element with specific value from the ArrayList myArrayList.RemoveAt(0); // Remove the element at specific index at the ArrayList Console.WriteLine($"Number of the elements are {myArrayList.Count}"); // number of elements double sum = 0; foreach (object obj in myArrayList) { if (obj is int) { sum += Convert.ToDouble(obj); } else if(obj is double) { sum += (double)obj; } else if (obj is string) { Console.WriteLine(obj); } } Console.WriteLine($"Sum is {sum}");
using System.Collections; HashTable studentsTable = new HashTable();
studentsTable.Add(student1.Id, student1);
Student storedStudent = (Student)studentsTable[student1.Id] // retrieve a student object with ID student1.Id
foreach(Student student in studentsTable.Values) { Console.WriteLine("{0}", student.Name) }
foreach(DictionaryEntry student in studentsTable) { Student temp = (Student)student.Value; }
HashTable table = new HashTable(); Student[] studentsArr = new Student[5]; studentsArr[0] = new Student(122, "Denis", "A"); foreach(Student student in studentsArr) { if (!table.ContainsKey(student.id)) { table.Add(student.id, student); } else { Console.writeLine("A student with the same ID already exist"); } }
using System.Collections.Generic; // contains one data type only Dictionary<TKey, TValue>
Dictionary<int, string> myDictionary = new Dictionary<int, string>(); OR Dictionary<int, string> myDictionary = new Dictionary<int, string>() { { 1, "one" } { 2, "two" } { 3, "three" }}
Dictionary<string, Employee> employeeDictionary = new Dictionary<string, Employee>(); foreach(Employee emp in employees) { employeeDictionary.Add(emp.role, emp); }
if (employeeDictionary.TryGetValue(key, out result)) { Console.WriteLine("Employee name", result.Name); } else { Console.WriteLine("The key does not exist"); }
string key = "CEO"; if (employeeDictionary.ContainsKey(key)) { Employee emp = employeeDictionary[key]; } else { Console.WriteLine("No employee found with {0} key", key); }
using System.Linq; for (int i = 0; i < employeeDictionary.Count; i++) { KeyValuePair<string, Employee> keyValuePair = employeeDictionary.ElementAt(i); // Print the key Console.WriteLine("Key: {0}, i is: {1}", keyValuePair.Key, i); // output: CEO // Storing the value in an employee object Employee employee = keyValuePair.Value; // Print a property of the employee Console.WriteLine("{0}", employee.Name); }
string key = "HR"; if (employeeDictionary.ContainsKey(key)) { employeeDictionary[key] = new Employee("HR", "Erika", 26); }
string key = "HR"; if (employeeDictionary.Remove(key)) // returns true if the item was removed { Console.WriteLine("Employee with role {0} was removed.", key); } else { Console.WriteLine("No employee was found with this key"); }
using System.Collections.Generic; // contains one data type only Stack<int> stack = new Stack<int>();
stack.Push(1);
int value = stack.Peek();
if (stack.Count > 0) { int value = stack.Pop(); }
int[] numbers = new int[] { 8, 2, 3, 4}; // Defining a new stack of int Stack<int> myStack = new Stack<int>(); foreach(int num in numbers) { myStack.Push(num); } Console.Write("The numbers in reverse are: "); while(stack.Count > 0) { Console.Write("{0} ", stack.Pop()); }
using System.Collections.Generic; // contains one data type only Queue<int> queue = new Queue<int>
queue.Enqueue(1);
int num = queue.Peek();
if (queue.Count > 0) int num = queue.Dequeue();
using System.Collections; // may contain different data types
using System.Collections; ... int num1 = 5; float num2 = 3.14f; string name = "John"; ArrayList myArrayList = new ArrayList(); myArrayList.Add(num1); myArrayList.Add(num2); myArrayList.Add(name); foreach(object element in myArrayList) { Console.WriteLine(element); }
using System.Collections.Generic; // contains one data type only
using System.Collections.Generic; ... string animal1 = "Cat"; string animal2 = "Dog"; string animal3 = "Flamingo"; List<string> myList = new List<string>(); myList.Add(animal1); myList.Add(animal2); myList.Add(animal3); foreach (string animal in myList) { Console.WriteLine(animal); }
// This is a single line comment
/* Multi lines comment. */
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { ... }
try { } catch(Exception e) { Console.WriteLine(e.Message); } finally // will be executed always { }
try { } catch(Exception) { throw; }
try { } catch { Console.WriteLine("Error"); }
try { Console.Write("Enter a number: "); double num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter a number: "); double num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(num1 / num2); } catch(DivideByZeroException e) { Console.WriteLine(e.Message); } catch(FormatException e) { Console.WriteLine(e.Message); } catch(Exception e) { Console.WriteLine(e.Message); } finally // will be executed always { }
throw new Exception("...");
At the right side of Visual Studio Open Solution Explorer Under Solution Right Click on current project name Press on Add > New Item Select a Class Give a name to the class with a capital lettter. As a result a new file with a Class was created.
At the main menu Project > Add a Class
// Books.cs namespace Giraffe { class Book { public string title; public string author; public int pages; } // Default constructor public Book() { } // Parameterized constructor public Book(string aTitle, string aAuthor, int aPages) { title = aTitle; // or this.title = aTitle; author = aAuthor; pages = aPages; } }
// Program.cs namespace Giraffe { class Program { static void Main(string[] args) { Book book1 = new Book("Harry Potter", "JK Rowling", 400); book1.title = "The hobbit"; // Update value Console.WriteLine(book2.title); Book book2 = new Book(); Console.ReadLine(); } } }
// Books.cs namespace Giraffe { class Book { public string title; public string author; public int pages; } }
// Program.cs namespace Giraffe { class Program { static void Main(string[] args) { Book book1 = new Book(); book1.title = "Harry Potter"; book1.author = "JK Rowling"; book1.pages = 400; Console.WriteLine(book1.title); Console.ReadLine(); } } }
~Book() { // Cleanup Statements when object of the class is runs out of scop Console.WriteLine("Deconstruction of the object"); Debug.WriteLine("Deconstruction of the object!"); }
// Student.cs namespace Giraffe { class Student { private string name; private string major; private double gpa; public Student(string aName, string aMajor, double aGpa) { name = aName; major = aMajor; gpa = aGpa; } public bool HasHonors() { if (gpa >= 3.5) { return true; } return false; } } }
// Program.cs namespace Giraffe { class Program { static void Main(string[] args) { Student student1 = new Student("Jim", "Business", 2.8); Console.WriteLine(student1.HasHonors()); // False Console.ReadLine(); } } }
// Movie.cs namespace Giraffe { class Movie { private string title; private string director; private string rating; public Movie(string aTitle, string aDirector, string aRating) { title = aTitle; director = aDirector; Rating = aRating; // rating will be set through the Rating setter. } public string Rating { get { return rating; } set { rating = value; } OR set { if (value == "G" || value == "PG") // value is a value that was passed { rating = value; } else { rating = "NR"; } } } } }
public string Rating { get; set; } // property // private string rating; is not required to be defined // Constructor will be: public Movie(aRating) { Rating = aRating; } Same as private string rating; // member value public string Rating { get { return this.rating; } set { this.rating = value; } }
// Program.cs namespace Giraffe { class Program { static void Main(string[] args) { Movie shrek = new Movie("Shrek", ""Adam Adamson, "PG"); Console.WriteLine(shrek.Rating); <--- using the getter shrek.Rating = "Cat"; <--- using the setter Console.ReadLine(); } } }
class Song { public static int songCount = 0; public static title; public Song(string aTitle) { title = aTitle; songCount++; } }
class Program { Song holiday = new Song("Holiday"); Console.WriteLine(Song.songCount); }
class UsefulTools { public static void SayHi(string name) { Console.writeLine("Hello " + name); } }
class Program { UsefulTools.SayHi("Mike"); }
static class UsefulTools // We cannot create an instance of the class { public static void SayHi(string name) { Console.writeLine("Hello " + name); } }
namespace InheritanceProj { // Parent class class ElectricDevice { public bool IsOn {get; set; } public string Brand { get; set; } public void SwitchOff() { IsOn = false; } public void SwitchOn() { IsOn = true; } public ElectricDevice(bool isOn, string brand) { IsOn = isOn; Brand = brand; } } }
namespace InheritanceProj { // Child class class Radio : ElectricDevice { public Radio(bool isOn, string brand) : base(isOn, brand) { } public void ListenRadio() { if (IsOn) { Console.WriteLine("Listening to the Radio"); } else { Console.WriteLine("Radio is switched off, switch it on first."); } } public void SwitchOn() { IsOn = true; } public void SwitchOff() { IsOn = false; } } }
namespace InheritanceProj { class Program { static void Main(string[] args) { Radio radio = new Radio(false, "LG"); // radio.SwitchOn(); radio.ListenRadio(); TV tv = new TV(true, "Sony"); tv.WhatchTV(); } } }
// Chef.cs namespace Giraffe { class Chef // A super class { public void MakeChicken() { Console.WriteLine("The Chef makes chicken"); } public void MakeSalad() { Console.WriteLine("The Chef makes salad"); } public virtual void MakeSpecialDish() // virtual - sub classes may override this method { Console.WriteLine("The Chef makes bbq ribs"); } } }
// ItalianChef.cs namespace Giraffe { class ItalianChef : Chef // inherits from Chef class - a sub class { public void MakePasta() { Console.WriteLine("The Chef makes pasta"); } public override void MakeSpecialDish() // override - overrides a virtual method { Console.WriteLine("The Chef makes chicken parm"); } } }
// Program.cs namespace Giraffe { class Program { static void Main(string[] args) { Chef chef = new Chef(); chef.MakeChicken(); chef.MakeSpecialDish(); ItalianChef italianChef = new ItalianChef(); italianChef.MakeChicken(); italianChef.MakeSpecialDish(); Console.ReadLine(); } } }
Console.ForegroundColor = ConsoleColor.Green; // Change color of the text Console.BackgroundColor = ConsoleColor.Gray; Console.Clear(); // Colors the whole console terminal in the background color Console.WriteLine("num1: " + num1); // Prints the content and jumps to a new line. Console.WriteLine("The value is {0}", num1); // Prints the content and jumps to a new line. Console.Write("Hello"); // Prints the text in the same line string input = Console.ReadLine(); // Takes a string or integer input and returns it as the Output value. int asciiValue = Console.Read(); // Takes a single input of type string and it returns the ASCII value of that input. Console.ReadKey(); // Takes a single input of type string and it returns the Key Info.
string name; Console.WriteLine("Please enter your name and press enter"); name = Console.ReadLine(); Console.WriteLine($"Hi {name}");
Console.WriteLine("Please Enter Your First name and press Enter"); string firstName = Console.ReadLine(); Console.WriteLine("Please Enter Your last name and press Enter"); string lastName = Console.ReadLine(); string fullName = string.Concat(firstName, " ", lastName); Console.WriteLine($"Welcome {fullName}");
Console.WriteLine("Please Enter Your First name and press Enter"); string firstName = Console.ReadLine(); Console.WriteLine("Please Enter Your last name and press Enter"); string lastName = Console.ReadLine(); string fullName = $"{firstName} {lastName}"; Console.WriteLine($"Welcome {fullName}");
Console.WriteLine("Please enter a string"); string inputStr = Console.ReadLine(); Console.WriteLine("Enter the character to search:"); char ch = Console.ReadLine()[0]; int indx = inputStr.IndexOf(ch); Console.WriteLine($"\n Index of char is {indx}");
Console.WriteLine("Please enter a string"); string inputStr = Console.ReadLine(); Console.WriteLine("Enter the character to search:"); ConsoleKeyInfo ch = Console.ReadKey(); Console.WriteLine(ch.KeyChar); int indx = inputStr.IndexOf(ch.KeyChar); Console.WriteLine($"\n Index of the char is {indx}");
using System.Threading; ... new Thread(() => { Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has started"); Thread.Sleep(1000); Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has ended"); }).Start();
new Thread(() => { Thread.Sleep(1000); Console.WriteLine("Thread 4"); }) { IsBackground = true }.Start();
using System; using System.Threading; namespace ThreadingE { class Program { static void Main(string[] args) { Console.WriteLine("Hello 1"); Thread.Sleep(1000); // stopping the main thread for 1 seconds Console.WriteLine("Hello 2"); Console.WriteLine("Hello 3"); Console.WriteLine("Hello 4"); Console.ReadKey(); } } }
new Thread(() => { Thread.Sleep(1000); Console.WriteLine("Thread 1"); }).Start(); new Thread(() => { Thread.Sleep(1000); Console.WriteLine("Thread 2"); }).Start(); new Thread(() => { Thread.Sleep(1000); Console.WriteLine("Thread 3"); }).Start();
using System.Threading; using System.Threading.Tasks; ... var taskCompletionSource = new TaskCompletionSource<bool>(); var thread = new Thread(() => { Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has started"); Thread.Sleep(1000); taskCompletionSource.TrySetResult(true); Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has ended"); }); // Console.WriteLine($"Thread Id: {thread.ManagedThreadId}"); thread.Start(); var result = taskCompletionSource.Task.Result; Console.WriteLine($"Task was done with result {result}");
Enumerable.Range(0, 1000).ToList().ForEach(f => { ThreadPool.QueueUserWorkItem((obj) => { Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has started"); Thread.Sleep(1000); Console.WriteLine($"Thread Id: {Thread.CurrentThread.ManagedThreadId} has ended"); }); });
namespace ThreadingE { class Program { static void Main(string[] args) { Console.WriteLine("Main Thread started"); Thread thread1 = new Thread(Thread1Function); Thread thread2 = new Thread(Thread2Function); thread1.Start(); thread2.Start(); thread1.Join(); // blocking the calling (here the main) thread Console.WriteLine("Thread1Function done"); thread2.Join(); Console.WriteLine("Thread2Function done"); Console.WriteLine("Main Thread ended"); Console.ReadKey(); } static void Thread1Function() { Console.WriteLine("Thread1Function started"); Thread.Sleep(3000); } static void Thread2Function() { Console.WriteLine("Thread2Function started"); } } }
namespace ThreadingE { class Program { static void Main(string[] args) { Console.WriteLine("Main Thread started"); Thread thread1 = new Thread(Thread1Function); Thread thread2 = new Thread(Thread2Function); thread1.Start(); thread2.Start(); if (thread1.Join(1000)) // timeout of 1 seconds { Console.WriteLine("Thread1Function done within 1 seconds"); } else { Console.WriteLine("Thread1Function wasn't done within 1 seconds"); } thread2.Join(); Console.WriteLine("Thread2Function done"); Console.WriteLine("Main Thread ended"); Console.ReadKey(); } static void Thread1Function() { Console.WriteLine("Thread1Function started"); Thread.Sleep(3000); Console.WriteLine("Thread1Function coming back to main"); } static void Thread2Function() { Console.WriteLine("Thread2Function started"); } } }
if (thread1.IsAlive) { Console.WriteLine("Thread1 is still doing staff"); } else { Console.WriteLine("Thread1 completed"); }
namespace ThreadingE { class Program { static void Main(string[] args) { Console.WriteLine("Main Thread started"); Thread thread1 = new Thread(Thread1Function); Thread thread2 = new Thread(Thread2Function); thread1.Start(); thread2.Start(); if (thread1.Join(1000)) // timeout of 1 seconds { Console.WriteLine("Thread1Function done within 1 seconds"); } else { Console.WriteLine("Thread1Function wasn't done within 1 seconds"); } thread2.Join(); Console.WriteLine("Thread2Function done"); for (int i = 0; i < 10; i++) { if (thread1.IsAlive) { Console.WriteLine("Thread1 is still doing staff"); Thread.Sleep(300); } else { Console.WriteLine("Thread1 completed"); } } Console.WriteLine("Main Thread ended"); Console.ReadKey(); } static void Thread1Function() { Console.WriteLine("Thread1Function started"); Thread.Sleep(3000); Console.WriteLine("Thread1Function coming back to main"); } static void Thread2Function() { Console.WriteLine("Thread2Function started"); } } }