Chapter 1.3 - Introduction To C#
Chapter 1.3 - Introduction To C#
NET
Introduction to C#
C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET
Framework. C# is used to develop web apps, desktop apps, mobile apps, games and
much more.
C# is an implementation of the object-orientation paradigm, which includes
encapsulation, inheritance, and polymorphism.
The design of C# closely maps to the design of Microsoft's Common Language Runtime
(CLR). The .NET Framework consists of the CLR and a set of libraries. The CLR is the
runtime for executing managed code.
Variables
Variable reserves a memory location, or a space in memory, for storing values. It is
called variable because the information stored in that location can be changed when the
program is running.
To use a variable, it must first be declared by specifying the name and data type.
A variable name, also called an identifier, can contain letters, numbers and the
underscore character (_) and must start with a letter or underscore.
Constants
Constants are immutable values which are known at compile time and do not change for
the life of the program. Constants are declared with the const modifier.
Only the C# built-in types (excluding System.Object) may be declared as const. User-
defined types, including classes, structs, and arrays, cannot be const.
Data Types
There are a number of built-in data types in C#. The most common are:
int - integer.
float - floating point number.
double - double-precision version of float.
char - a single character.
bool - Boolean that can have only one of two values: True or False.
string - a sequence of characters.
Declare Variables in C#
The syntax for variable definition in C#
<data_type> <variable_name>;
<data_type> <variable_name>=value;
<access_specifier><data_type> <variable_name>=value;
Here,
<data_type> is a type of data in which the variable can hold the types they are an integer,
Sting, float and so on.
<variable_name> is the name of a variable that holds the value in our application
<value> is assigning a specific value to the variable
<access_specifier> is used to give access permission for the variable. They are some
suitable methods to describe the variable names in c# programming language.
int name;
float value;
char _firstname;
Initialize Variables in C#
To assign a value to a variable called initialization, variables can be initialized with an
equal sign by the constant expression, variables can also be initialized at their
declaration.
Syntax:
<data_type> <variable_name> = value;
Or
variable_name = value;
For example,
int value1=5, value2= 7;
double pi= 3.1416;
char name='Rock';
Operators
C# provides a number of operators. Many of them are supported by the built-in
types and allow you to perform basic operations with values of those types. Those
operators include the following types:
(i). Arithmetic operators that perform arithmetic operations with numeric operands
(ii). Comparison operators that compare numeric operands
(iii). Boolean logical operators that perform logical operations with bool operands
(iv). Bitwise and shift operators that perform bitwise or shift operations with operands of
the integral types
(v). Equality operators that check if their operands are equal or not
Arithmetic operators
The following operators perform arithmetic operations with operands of numeric
types:
Unary ++ (increment), -- (decrement), + (plus), and - (minus) operators
Binary * (multiplication), / (division), % (remainder), + (addition),
and - (subtraction) operators
Those operators are supported by all integral and floating-point numeric types.
The following list orders arithmetic operators starting from the highest precedence
to the lowest:
Postfix increment x++ and decrement x-- operators
Prefix increment ++x and decrement --x and unary + and - operators
Multiplicative *, /, and % operators
Additive + and - operators
Binary arithmetic operators are left-associative. That is, operators with the same
precedence level are evaluated from left to right.
Use parentheses, (), to change the order of evaluation imposed by operator
precedence and associativity.
Comparison operators
The < (less than), > (greater than), <= (less than or equal), and >= (greater than or
equal) comparison, also known as relational, operators compare their operands.
Those operators are supported by all integral and floating-point numeric types.
Operator precedence
The following list orders bitwise and shift operators starting from the highest
precedence to the lowest:
Bitwise complement operator ~
Shift operators <<, >>, and >>>
Logical AND operator &
Logical exclusive OR operator ^
Logical OR operator |
Equality operators
The == (equality) and != (inequality) operators check if their operands are equal or
not.
C# Type Casting
Type casting is when you assign a value of one data type to another type.
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
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size
type:
Example
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in front of the
value:
Example
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
The if Statement
The if statement is a conditional statement that executes a block of code when a condition is true.
namespace cbt
{
class Program
{
static void Main(string[] args)
{
int x = 8;
int y = 3;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
}
}
}
The code above will evaluate the condition x > y. If it is true, the code inside the if block will
execute.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cbt
{
class Program
{
static void Main(string[] args)
{
int mark = 85;
if (mark < 50)
{
Console.WriteLine("You failed.");
}
else
{
Console.WriteLine("You passed.");
}
}
}
}
switch
The switch statement provides a more elegant way to test a variable for equality against a list of
values.
Each value is called a case, and the variable being switched on is checked for each switch case.
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int num = 3;
switch (num)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
case 3:
Console.WriteLine("three");
break;
}
}
}
}
In a switch statement, the optional default case is executed when none of the previous cases
match.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cbt
{
class Program
{
static void Main(string[] args)
{
int age = 88;
switch (age) {
case 16:
Console.WriteLine("Too young");
break;
case 42:
Console.WriteLine("Adult");
break;
case 70:
Console.WriteLine("Senior");
break;
default:
Console.WriteLine("The default case");
break;
}
}
}
}
This behavior is called fallthrough and modern C# compilers will not compile such code. All
case and default code must end with a break statement.
while
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int num = 1;
while(num < 6)
{
Console.WriteLine(num);
num++;
}
}
}
}
The example above declares a variable equal to 1 (int num = 1). The while loop checks the
condition (num < 6) and, if true, executes the statements in its body, which increment the value
of num by one, before checking the loop condition again.
After the 5th iteration, num equals 6, the condition evaluates to false, and the loop stops running.
do-while
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
int a = 0;
do {
Console.WriteLine(a);
a++;
} while(a < 5);
}
}
}
The example above declares a variable equal to 1 (int num = 1). The while loop checks the
condition (num < 6) and, if true, executes the statements in its body, which increment the value
of num by one, before checking the loop condition again.
A for loop executes a set of statements a specific number of times, and has the syntax:
for ( init; condition; increment ) {
statement(s);
}
For example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
for (int x = 10; x < 15; x++)
{
Console.WriteLine("Value of x: {0}", x);
}
}
}
}
Value of x: 10
Value of x: 11
Value of x: 12
Value of x: 13
Value of x: 14
foreach
C# provides an easy to use and more readable alternative to for loop, the foreach loop when
working with arrays and collections to iterate through the items of arrays/collections. The
foreach loop iterates through each item, hence called foreach loop.
John
Tom
Peter
If the continue statement is used within the loop body, it immediately goes to the next iteration
skipping the remaining code of the current iteration.
John
Peter
If the break statement is used within the loop body, it stops the loop iterations and goes
immediately after the loop body.
John
OK
For a developer who writes queries, the most visible "language-integrated" part of
LINQ is the query expression. Query expressions are written in a declarative query
syntax. By using query syntax, you can perform filtering, ordering, and grouping
operations on data sources with a minimum of code. You use the same basic query
expression patterns to query and transform data in SQL databases, ADO .NET
Datasets, XML documents and streams, and .NET collections.
The following example shows the complete query operation. The complete operation
includes creating a data source, defining the query expression, and executing the
query in a foreach statement.
{
Console.Write(i + " ");
}
// Output: 97 92 81