C# is a programming language that is part of the .Net framework => used for writing .Net applications
.NET Intro
- - designed and maintained by Microsoft
- - .NET programs needs a VM, called Common Language Runtime (CLR), to run on a host
- C# code >> Compiler >> Common Language Runtime (CLR) -adds type safety >> Machine code
- - C# and C++ can both access .NET framework and can communicate with each other
C# Intro
- - used to develop: mobile apps, desktop apps, web apps, web services, websites, games, VR, DB apps
- To run a C# file in MacOS:
- save the file as: anyfilename.cs
- need to have mono installed
- execute:> brew install mono
- execute:> export PATH=/Library/Frameworks/Mono.framework/Versions/Current/bin/:${PATH}
- execute:> mcs anyfilename.cs // this will create an executable: anyfilename.exe
- execute:> mono anyfilename
Creating a .NET project in C#
.NET Project in C# - Setup
1) Install C# extension in VS Code
2) Download and install .NET SDK 5.0 such that when you type in terminal: dotnet --version
- delete dotnet file in /usr/local/bin/
- execute: ln -s /usr/local/share/dotnet/dotnet /usr/local/bin/
3) Create an empty folder in your device
4) Open VS Code > File > Open.. > [select your folder] - click open
5) Open VS Code terminal: View > terminal
6) In VS Code terminal:> dotnet new console // this creates a new project in your folder
7) In VS Code: File > save
8) In VS Code terminal:> dotnet run // runs simple hello world prog
1) Install C# extension in VS Code
2) Download and install .NET SDK 5.0 such that when you type in terminal: dotnet --version
- delete dotnet file in /usr/local/bin/
- execute: ln -s /usr/local/share/dotnet/dotnet /usr/local/bin/
3) Create an empty folder in your device
4) Open VS Code > File > Open.. > [select your folder] - click open
5) Open VS Code terminal: View > terminal
6) In VS Code terminal:> dotnet new console // this creates a new project in your folder
7) In VS Code: File > save
8) In VS Code terminal:> dotnet run // runs simple hello world prog
|
Notes about .NET and C#
|
|
Visual Studio (not Visual Studio Code) can be used to create .NET projects
ie: ASP, MAUI, .NET Core - WPF, and etc.
Basics
Basics
- using System; // allows us to use classes from System namespace
- namespace HelloWorld // container for classes and other namespaces
- {
- class Program // container for methods and attribues
- {
- static void Main(string[] args) // the Main method always executes
- {
- Console.WriteLine("Hello World!"); // Console is a class of Systems namespace
- }
- }
- }
Variables
- Syntax: type variableName = value; // list of data types are similar to Java but in C# => string, not String
- bool myBool = true;
- string myText = "Hello";
- Constants
- const int myNum = 15; // must be assigned a value when initialized
- myNum = 20; // error
- Example
- string firstName = "Kannika ";
- string lastName = "Kabilar";
- string fullName = firstName + lastName; // equavalent to string.Concat(firstName, lastName)
- Console.WriteLine(fullName);
// Declare many variables
- int a = 5, b = 6, c = 50;
- int x, y, z;
- x = y = z = 50;
// long must end with L, double with D, and float with F
- long myNum = 15000000000L;
- double myNum = 19.99D;
- float myNum = 5.75F;
Type Casting in C#
- Implicit Casting (automatically) - converting a smaller type to a larger type size
- char -> int -> long -> float -> double
- Ex:
- int myInt = 9;
- double myDouble = myInt; // Automatic casting: int to double
- Console.WriteLine(myDouble is double); // True (can also use typeof() or myInt.GetType())
- Explicit Casting (manually) - converting a larger type to a smaller size type
- double -> float -> long -> int -> char
- Ex:
- double myDouble = 9.78;
- int myInt = (int) myDouble; // Manual casting: double to int
- Console.WriteLine(myDouble); // Outputs 9.78
- Console.WriteLine(myInt); // Outputs 9
- Using built-in methods for type casting:
- Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long)
- int myInt = 10;
- Console.WriteLine(Convert.ToString(myInt)); // convert int to string
User Input
Operators are similar to Java
Math
String
- string interpolation
- access strings
- Console.WriteLine("Enter your age:");
- int age = Convert.ToInt32(Console.ReadLine());
- // ReadLine outputs a string, so it needs to be typecasted into int
- Console.WriteLine("Your age is: " + age);
Operators are similar to Java
- Arithmetic: +, -, *, /, %, ++, --
- Assignment: =, +=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=
- Comparison: ==, !=, >, <, >=, <=
- Logical: &&, ||, !
Math
- Math.Max(5, 10); // 10 (also available: Math.Min(5, 10); => 5)
- Math.Sqrt(64); // 8
- Math.Abs(-2.5); // 2.5
- Math.Round(9.99); // 10
String
- string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- Console.WriteLine("The length of the txt string is: " + txt.Length); // 26
- Console.WriteLine(txt.ToLower()); // abcdefghijklmnopqrstuvwxyz (txt.ToUpper() capitalizes)
- string interpolation
- string firstName = "Kannika";
- string lastName = "Kabilar";
- string name = $"My full name is: {firstName} {lastName}";
- Console.WriteLine(name); // My full name is: Kannika Kabilar
- access strings
- string name = "Nina Williams";
- Console.WriteLine(myString[1]); // Outputs "i"
- int charPos = name.IndexOf("W");
- // Get last name
- string lastName = name.Substring(charPos);
- Console.WriteLine(lastName);
- string txt = "Special characters in string: \\ is backslash, \' is single quote, \" is double quote";
- // \n - newline; \t - tab; \b - backspace
If... else if... else...
- Shorthand of if... else...
Switch statements, For-loops, break and continue are exactly like Java's
// for-each loop is a little different
- int age = 23;
- if (age < 12) {
- Console.WriteLine("You are a child");
- }else if (age < 18) {
- Console.WriteLine("You are a teen");
- } else {
- Console.WriteLine("You are an adult");
- } // Outputs "You are an adult"
- Shorthand of if... else...
- Syntax: variable = (condition) ? expressionTrue : expressionFalse;
- int age = 23;
- string result = (age < 18) ? "Not old enough to vote" : "You can vote";
- Console.WriteLine(result); // You can vote
Switch statements, For-loops, break and continue are exactly like Java's
// for-each loop is a little different
- string[] cars = {"Lambo", "BMW", "Ferrari", "McLaren"};
- foreach (string i in cars)
- {
- Console.WriteLine(i);
- }
Arrays in C#
- Creating arrays
- Creating arrays
- string[] cars = new string[4]; // Create an array of four elements, and add values later
- string[] cars = new string[4] {"Lambo", "BMW", "Ford", "McLaren"}; // Create an array of four elements and add values right away
- string[] cars = new string[] {"Lambo", "BMW", "Ford", "McLaren"}; // Create an array of four elements without specifying the size
- string[] cars = {"Lambo", "BMW", "Ford", "McLaren"};
- // Create an array of four elements, w/o the new keyword, or specifying the size
- -
- string[] cars;
- cars = {"Volvo", "BMW", "Ford"}; // This would cause an error
- cars = new string[] {"Volvo", "BMW", "Ford"}; // This will work
- -
- Console.WriteLine(cars.Length); // 4
- cars[2] = "Chevrolet"; // values can be changed like this
- -
- Array.Sort(cars); // sort alphabetically or numerically
- -
- // Other useful array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace
- using System.Linq;
- ...
- int[] myNumbers = {5, 1, 8, 9};
- Console.WriteLine(myNumbers.Max()); // returns the largest value
- Console.WriteLine(myNumbers.Min()); // returns the smallest value
- Console.WriteLine(myNumbers.Sum()); // returns the sum of elements
- -
- // 1 comma int[,] => 2-D array, 2 comma int[,,] => 3-D array
- int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
- Console.WriteLine(numbers[0, 2]); // Outputs 2
- -
- // Looping through 2-D arrays
- int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
- -
- for (int i = 0; i < numbers.GetLength(0); i++)
- {
- for (int j = 0; j < numbers.GetLength(1); j++)
- {
- Console.WriteLine(numbers[i, j]);
- }
- }
C# Methods/Functions
Methods/Functions
Why use methods? - a block of code that can re-used many times
Parameters
- When a parameter is passed to the method, it is called an argument
- Methods in C# can be overloaded. Multiple methods can have the same name as long as the number and/or type of parameters are different.
- class Program
- {
- static void MyMethod() // static means the method belongs to class Program and not an object of the Program
- {
- // code to be executed
- }
- }
Parameters
- When a parameter is passed to the method, it is called an argument
- static int MyMethod(int x = 2, int y = 2) // Default values of x and y are 2
- {
- return (5 + x) - y;
- }
- static void Main(string[] args)
- {
- Console.WriteLine(MyMethod(7, 2)); // 10
- Console.WriteLine(MyMethod()); // 5
- Console.WriteLine(MyMethod(y: 3, x: 7)); // 9 | sending arguments with the key: value syntax so order doesn't matter
- }
- Methods in C# can be overloaded. Multiple methods can have the same name as long as the number and/or type of parameters are different.
Classes in C#
- Creating an object of a class and accessing it in another class
This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the Main() method (code to be executed)).
Example
This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the Main() method (code to be executed)).
Example
Example + Constructors
|
// prog1.cs
using System; // this does not need to be included if namespace in prog2.cs is also MyApplication using MyApplication2; namespace MyApplication { class Program { static void Main(string[] args) { Car myObj = new Car(); Console.WriteLine(myObj.color); } } } |
// prog2.cs
using System; namespace MyApplication2 { class Car { public string color = "blue"; } } |
Constructors
- constructors save time and they can be overloaded
class Car
{
public string model; // All attributes and methods of a class are called: Class members
public Car(string modelName, string modelColor, int modelYear) // constructor name must match class name
{
model = modelName;
color = modelColor;
year = modelYear;
}
static void Main(string[] args)
{
// Create an object of the Car Class (this will call the constructor - if not implemented C# will have a default one)
Car Lambo = new Car("Aventador", "Blue", 2023);
Console.WriteLine(Lambo.model); // Aventador
}
}
- constructors save time and they can be overloaded
class Car
{
public string model; // All attributes and methods of a class are called: Class members
public Car(string modelName, string modelColor, int modelYear) // constructor name must match class name
{
model = modelName;
color = modelColor;
year = modelYear;
}
static void Main(string[] args)
{
// Create an object of the Car Class (this will call the constructor - if not implemented C# will have a default one)
Car Lambo = new Car("Aventador", "Blue", 2023);
Console.WriteLine(Lambo.model); // Aventador
}
}
Access Modifiers
- Code within following modifier indicate that they are available to be accessed by
- Public - all classes
- Protected - same package and subclasses
- Default - same package only
- Internal - within its own assembly (namespace ?)
- By default, all members of a class are private if no access modifier is specified
Access Modifier Example
- class Fruit
{
public string type = "Apple"; - string color = "red"; // private by default
- private int amount = 5;
- }
class Program
{
static void Main(string[] args)
{
Fruit myObj = new Fruit();
Console.WriteLine(myObj.type); // accessible: Apple - Console.WriteLine(myObj.color); // not accessible: Error
- Console.WriteLine(myObj.amount); // not accessible: Error
}
}
Properties w/ Encapsulation
- A property is like a combination of a variable and a method, and it has two methods: a get and a set
- Properties are used to implement encapsulation
- It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter
- Properties are used to implement encapsulation
- It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter
Encapsulation w/ Properties example
|
// Automatic Properties
class Person { public string Name // property { get; set; } } |
Inheritance
- attributes/fields and methods of one class can be used in another class
- Derived Class (child) - the class that inherits from another class
- Base Class (parent) - the class being inherited from
Inheritance example
- class Fish // base class (parent)
- {
- public string habitat = "Ocean"; // Fish field
- public void move() // Fish method
- {
- Console.WriteLine("Swimming...");
- }
- }
- class Shark : Fish // derived class (child)
- {
- public string name = "Sharkie";
- }
- class Program
- {
- static void Main(string[] args)
- {
- // Create a Shark object
- Shark myShark = new Shark();
- myShark.move(); // Swimming | Calling from Fish class
- Console.WriteLine(myShark.name + " lives in the " + myShark.habitat); // Sharkie lives in the Ocean
- }
- }
Polymorphism works a little differently in C#
Polymorphism example C#
- class Animal // Base class (parent)
- {
- public virtual void animalSound() // virtual keyword allows child class to override this method
- {
- Console.WriteLine("The animal makes a sound");
- }
- }
- class Pig : Animal // Derived class (child)
- {
- public override void animalSound() // override keyword used to override methods from parent class
- {
- Console.WriteLine("The pig says: wee wee");
- }
- }
- class Dog : Animal // Derived class (child)
- {
- public override void animalSound()
- {
- Console.WriteLine("The dog says: bow wow");
- }
- }
- class Program
- {
- static void Main(string[] args)
- { // Below is performing polymorphism
- Animal myAnimal = new Animal(); // Create a Animal object
- Animal myPig = new Pig(); // Create a Pig object
- Animal myDog = new Dog(); // Create a Dog object
- myAnimal.animalSound(); // "The animal makes a sound"
- myPig.animalSound();
- // "The pig says: wee wee" | w/o virtual and override keyword, it will say: The animal makes a sound
- myDog.animalSound(); // "The dog says: bow wow"
- }
- }
Abstract Class in C# is similar to Java
Abstract class example
abstract class Animal
{
// Abstract method (does not have a body) and can only exist in abstract classes
public abstract void animalSound();
public void sleep() // Abstract classes can have regular methods
{
Console.WriteLine("Zzz");
}
}
class Pig : Animal // Derived class (inherit from Animal)
{
public override void animalSound() // must use override keyword to override from parent class
{
Console.WriteLine("The pig says: wee wee"); // The body of animalSound() must be implemented here
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object because abstract classes cannot be used to create an object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}
{
// Abstract method (does not have a body) and can only exist in abstract classes
public abstract void animalSound();
public void sleep() // Abstract classes can have regular methods
{
Console.WriteLine("Zzz");
}
}
class Pig : Animal // Derived class (inherit from Animal)
{
public override void animalSound() // must use override keyword to override from parent class
{
Console.WriteLine("The pig says: wee wee"); // The body of animalSound() must be implemented here
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object because abstract classes cannot be used to create an object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}
Interfaces
- Interface methods & properties are by default abstract and public
Interface Example
interface IAnimal // good practice to start interface names with "I"
{ // Interfaces can only have properties (get, set methods) or methods, no attributes
void animalSound(); // interface method cannot have a body
}
class Pig : IAnimal // Pig "implements" the IAnimal interface and it can implement other interfaces too
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee"); // All methods of interface must be overriden
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object because interface cannot be used to create an object
myPig.animalSound();
}
}
{ // Interfaces can only have properties (get, set methods) or methods, no attributes
void animalSound(); // interface method cannot have a body
}
class Pig : IAnimal // Pig "implements" the IAnimal interface and it can implement other interfaces too
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee"); // All methods of interface must be overriden
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object because interface cannot be used to create an object
myPig.animalSound();
}
}
Enums
Enums example
- enum Level
- {
- Low, // 0
- Medium, // 1
- High, // 2
- Ultra=100, // assigning my own value to enum
- Mega // 101
- }
- Level myVar = Level.Medium;
- // myNum = 2 | because each element has an integer equivalent starting from 0
- int myNum = (int) Level.High;
Structs in C#
- Structs can have methods and can implement interfaces
- Can be instantiated (ie: Books book1;) but struct object cannot be used until all fields are initialized
- classes are reference types and structs are value types
Structs Examples
|
using System;
struct Books { public string title; public string author; public string subject; public int book_id; }; public class testStructure { public static void Main(string[] args) { Books Book1; /* Declare Book1 of type Book */ /* book 1 specification */ Book1.title = "C Programming"; Book1.author = "Nuha Ali"; Book1.subject = "C Programming Tutorial"; Book1.book_id = 6495407; /* print Book1 info */ Console.WriteLine( "Book 1 title : {0}", Book1.title); Console.WriteLine("Book 1 author : {0}", Book1.author); Console.WriteLine("Book 1 subject : {0}", Book1.subject); Console.WriteLine("Book 1 book_id :{0}", Book1.book_id); Console.ReadKey(); } } |
using System;
struct Books { private string title; private string author; private int book_id; public void getValues(string t, string a, int id) { title = t; author = a; book_id = id; } public void display() { Console.WriteLine("Title : {0}", title); Console.WriteLine("Author : {0}", author); Console.WriteLine("Book_id :{0}", book_id); } }; public class testStructure { public static void Main(string[] args) { Books Book1 = new Books(); /* book 1 specification */ Book1.getValues("C Programming", "Nuha Ali", 6495407); Book1.display(); /* print Book1 info */ Console.ReadKey(); } } |
Regex in C#
Regex example
- // matches words that start with letter 'm' and end with 'e'
- using System;
- using System.Text.RegularExpressions;
- namespace RegExApplication {
- class Program {
- private static void showMatch(string text, string expr) {
- Console.WriteLine("The Expression: " + expr);
- MatchCollection mc = Regex.Matches(text, expr);
- foreach (Match m in mc) {
- Console.WriteLine(m);
- }
- }
- static void Main(string[] args) {
- string str = "make maze and manage to measure it";
- Console.WriteLine("Matching words start with 'm' and ends with 'e':");
- showMatch(str, @"\bm\S*e\b");
- Console.ReadKey();
- }
- }
- }
Threads in C#
Threads example
- using System;
- using System.Threading;
- namespace MultithreadingApplication {
- class ThreadCreationProgram {
- public static void CallToChildThread() {
- try {
- Console.WriteLine("Child thread starts");
- // do some work, like counting to 10
- for (int counter = 0; counter <= 10; counter++) {
- Thread.Sleep(500);
- Console.WriteLine(counter);
- }
- Console.WriteLine("Child Thread Completed");
- } catch (ThreadAbortException e) {
- Console.WriteLine("Thread Abort Exception");
- } finally {
- Console.WriteLine("Couldn't catch the Thread Exception");
- }
- }
- static void Main(string[] args) {
- ThreadStart childref = new ThreadStart(CallToChildThread);
- Console.WriteLine("In Main: Creating the Child thread");
- Thread childThread = new Thread(childref);
- childThread.Start();
- //stop the main thread for some time
- Thread.Sleep(2000);
- //now abort the child
- Console.WriteLine("In Main: Aborting the Child thread");
- childThread.Abort();
- Console.ReadKey();
- }
- }
- }
Try... Catch... Finally... syntax is exactly same as Java
Nullable
int? num1 = null; // <type> varname = value; allows null value anong w/ int values
int? num2 = 45;
num3 = num1 ?? 9; // num3 = 9 because num1 is null
num4 = num2 ?? 9; // num4 = 45 because num2 is not null
Nullable
int? num1 = null; // <type> varname = value; allows null value anong w/ int values
int? num2 = 45;
num3 = num1 ?? 9; // num3 = 9 because num1 is null
num4 = num2 ?? 9; // num4 = 45 because num2 is not null
Some other maybe important concepts in C#
- Reflection objects are used for obtaining type information at runtime
- An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array.
- C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the reference to a method
- Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur.
- Collection classes are specialized classes for data storage and retrieval. These classes provide support for stacks, queues, lists, and hash tables. Most collection classes implement the same interfaces. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
- *?! - Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
- Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body.
- C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.
ASP (Active Server Page)
- - ASP is similar to PHP in which normal html webpages can be made dynamic and more interactive with ASP
- - ASP allows server code written in C# or Visual Basic to be embedded in html files
- => Razor Markup - embeds C# or VB in ASP.NET web pages
- C# code blocks are enclosed in @{ ... }
- Inline expressions (variables or functions) start with @
- Variables are declared with the var keyword, OR the datatype (int, string, etc.)
- C# files have the extension .cshtml
- With Web Pages you can use the @RenderPage() method to import content from separate files.
- ex: @RenderPage("header.cshtml")
- File name that starts with "_" cannot be browsed from web - ie: _header.cshtml, and _AppStart.chtml contains sensitive info
EXAMPLE
<!-- Single statement block -->
@{ var myMessage = "Hello World"; }
@{ string myMessage2 = "Hi Kannika"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<!-- For loop example -->
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
<p>The greeting is: @greetingMessage</p>
@{ var myMessage = "Hello World"; }
@{ string myMessage2 = "Hi Kannika"; }
<!-- Inline expression or variable -->
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<!-- For loop example -->
@for(var i = 10; i < 21; i++)
{<p>Line @i</p>}
<ul>
@foreach (var x in Request.ServerVariables)
{<li>@x</li>}
</ul>
<p>The greeting is: @greetingMessage</p>
ASP.NET Core in C# using MVC
ASP.NET Core in C# using MVC
When a user clicks something or enters a url
- The Views folder contains *.cshtml web pages which are html webpages with C sharp code (Razor HTML)
- Model: manages the behavior and data. It contains classes and objects. It uses SQL statements to get data from database and sends it to controller through objects.
- Controller: handles page events and navigation between pages
When a user clicks something or enters a url
- => this request is sent to the router
- => the router calls the controller and tells what info has been requested
- => the controller calls methods from the model to get this list of info
- => the model gets the info from a stored database and send it back to controller
- => the controller sends this info to be displayed in a webpage in Views
- => this webpage is sent from Views to controller and the controller sends this webpage to the user