C# Quick Start
C# is a programming language developed by Microsoft that runs on the .NET framework.
1. Syntax
1.1 Hello World
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
- Every C# statement ends with a semicolon
;
using System
means that we can use classes from theSystem
namespacenamespace
is used to organize your code, and it is a container for classes and other namespaceclass
is a container for data and methods
1.2 Comments
Single-line Comments
Start with two forward slashes //
.
// this is a comment
Console.WriteLine("Hello"); // Comment here
Multi-line Comments
Start with /*
and ends with */
, any text between these will be ignored by C#.
/* This is the
* multi-line Comment
*/
Console.WriteLine("Hello World");
1.4 Variables
Declare Variables
// Single varible
// type variableName = value;
int myAge = 10;
string name;
// Mutilple variables
/// type n1 = v1, n2 = v2 ...
int x = 1, y =2;
int u, v;
Constants
Add const
keyword in front of the variable type will declare it as “constant” which means unchanged and read-only.
const in myAge = 10;
// error
// myAge = 11;
Identifier
All C# variables must be identified with unique names that called identifiers.
Rules of naming variables :
- Can contain letters, digits and the underscore character
_
- Must begin with a letter
- Should start with a lowercase letter and cannot contain whitespace
- Cannot use reserved words like
int
,double
…
2. Data Type
Data Type | Size | Description |
---|---|---|
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
bool | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter, surrounded by single quotes |
string | 2 bytes per character | Stores a sequence of characters, surrounded by double quotes |
2.1 Type Casting
In C#, there are two types of casting:
- Implicit Casting (automatically) - converting a smaller type to a larger type size
char
->int
->long
->float
->double
- Explicit Casting (manually) - converting a larger type to a smaller size type
double
->float
->long
->int
->char
. It is also possible to convert data types explicitly by using built-in methods, such asConvert.ToBoolean
,Convert.ToDouble
,Convert.ToString
,Convert.ToInt32
(int
) andConvert.ToInt64
(long
).
3. Operators
Arithmetic operators
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | x++ |
-- | Decrement | Decreases the value of a variable by 1 | x-- |
Assignment operators:
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Comparison operators
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Logical Operators
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns True if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns True if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns False if the result is true | !(x < 5 && x < 10) |
4. Flow Control
4.1 If-else
If-else if :
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
4.2 Switch
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
4.3 Loop
While
while (condition)
{
// code block to be executed
}
Do-while
do
{
// code block to be executed
}
while (condition);
For
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Foreach
foreach (type variableName in arrayName)
{
// code block to be executed
}
5. Array
To declare a array, define the variable type with square brackets:
string[] cars;
string[] names {"A", "B"};
Console.WriteLine(names[0]); // access array element
Console.WriteLine(names.Length); // get length of array
6. Method
class Program
{
static void MyMethod(parameters declaration)
{
// code to be executed
}
}
static void Main(string[] args)
{
MyMethod(parameters);
}
It is good practice to start with an uppercase letter when naming methods.
6.1 Default Method Value
static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}
static void Main(string[] args)
{
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
}
// Sweden
// India
// Norway
// USA
6.2 Named Arguments
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}
static void Main(string[] args)
{
MyMethod(child3: "John", child1: "Liam", child2: "Liam");
}
// The youngest child is: John
6.3 Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
int MyMethod(int x)
float MyMethod(float x)
double MyMethod(double x, double y)
7. OOP
7.1 Class
class ClassName
{
// Class Members
// fields
type fieldName = value;
// methods
public void MethodName(...)
{
//...
}
public static void StaticMethodName(...)
{
//...
}
}
Fields and methods inside classes are referred to as “Class Members”.
Objects
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
use new
to create objects.
Constructor
A special method to initialize objects.
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Outputs "Mustang"
7.2 Access Modifiers
Modifier | Description |
---|---|
public | The code is accessible for all classes |
private | The code is only accessible within the same class |
protected | The code is accessible within the same class, or in a class that is inherited from that class. |
internal | The code is only accessible within its own assembly, but not from another assembly. |
7.3 Properties And Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:
- declare fields/variables as
private
- provide
public
get
andset
methods, through properties, to access and update the value of aprivate
field
class Person
{
private string name; // field
public string Name // property
{
get { return name; } // get method
set { name = value; } // set method
}
}
Automatic Properties
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
7.4 Inheritance
It’s possible to inherit fields and methods from one class to another, and “inheritance concept” can grouped into 2 categories:
- Derived Class (child): the class that inherits from another class
- Base Class (parent): the class being inherited from
Use :
to inherit from a class :
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
7.5 Polymorphism
class Animal // Base class (parent)
{
public void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
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();
myPig.animalSound();
myDog.animalSound();
}
}
output:
The animal makes a sound
The animal makes a sound
The animal makes a sound
The output from the example above was probably not what you expected. That is because the base class method overrides the derived class method, when they share the same name.
C# provides an option to override the base class method, by adding the virtual
keyword to the method inside the base class, and by using the override
keyword for each derived class methods:
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public override void animalSound()
{
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)
{
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();
myPig.animalSound();
myDog.animalSound();
}
}
The animal makes a sound
The pig says: wee wee
The dog says: bow wow
7.6 Abstract Classes and Methods
The abstract
keyword is used for classes and methods:
- Abstract Class: is restricted class that cannot be used to create objects
- Abstract Method: can only be used in an abstract class, and it does not have a body.
abstract class Animal
{
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
7.7 Interface
Interface can only contain abstract methods and properties.
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
- Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "IAnimal" object in the Program class)
- Interface methods do not have a body - the body is provided by the "implement" class
- On implementation of an interface, you must override all of its methods
- Interfaces can contain properties and methods, but not fields/variables
- Interface members are by default
abstract
andpublic
- An interface cannot contain a constructor (as it cannot be used to create objects)
7.8 Enum
An enum
is special class
that represents a group of constants.
enum Level
{
Low,
Medium,
High
}
// ...
Level myVar = Level.Medium;
Console.WriteLine(myVar);
Enum inside Class
class Program
{
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
Console.WriteLine(myVar);
}
}
Enum values
By default, the first item of an enum
has the value 0, the second is 1 and so on.
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July, // 6
Sept = 9 // you can set specific value
}
static void Main(string[] args)
{
int myNum = (int) Months.April;
Console.WriteLine(myNum);
}
Enum with Switch
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
switch(myVar)
{
case Level.Low:
Console.WriteLine("Low level");
break;
case Level.Medium:
Console.WriteLine("Medium level");
break;
case Level.High:
Console.WriteLine("High level");
break;
}
}
Reference
- C# Tutorial W3schools