You are on page 1of 13

Unit-1: Introduction to .NET Framework and 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.

The statements below use C# data types:


int x = 42;
double pi = 3.14;
char y = 'Z';
bool isOnline = true;
string firstName = "David";

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;

Component Based Technology


1
Unit-1: Introduction to .NET Framework and C#.NET

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.

Operator precedence and associativity

Component Based Technology


2
Unit-1: Introduction to .NET Framework and C#.NET

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.

Boolean logical operators


The following operators perform logical operations with bool operands:
 Unary ! (logical negation) operator.
 Binary & (logical AND), | (logical OR), and ^ (logical exclusive OR) operators. Those
operators always evaluate both operands.
 Binary && (conditional logical AND) and || (conditional logical OR) operators. Those
operators evaluate the right-hand operand only if it's necessary.
For operands of the integral numeric types, the &, |, and ^ operators perform bitwise
logical operations. For more information, see Bitwise and shift operators.

Bitwise and shift operators


The following operators perform bitwise or shift operations with operands of
the integral numeric types or the char type:
 Unary ~ (bitwise complement) operator
 Binary << (left shift), >> (right shift), and >>> (unsigned right shift) operators
 Binary & (logical AND), | (logical OR), and ^ (logical exclusive OR) operators

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 |

Component Based Technology


3
Unit-1: Introduction to .NET Framework and C#.NET

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

Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

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

Type Conversion Methods


It is also possible to convert data types explicitly by using built-in methods, such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int)
and Convert.ToInt64 (long):
Example
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to
string

Component Based Technology


4
Unit-1: Introduction to .NET Framework and C#.NET

The if Statement

The if statement is a conditional statement that executes a block of code when a condition is true.

The general form of the if statement is:


if (condition)
{
// Execute this code when condition is true
}

The condition can be any expression that returns true or false.


For 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 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.

The else Clause

An optional else clause can be specified to execute a block of code when the condition in


the if statement evaluates to false.
Syntax:
if (condition)
{
//statements
}
else
{
//statements
}
using System;

Component Based Technology


5
Unit-1: Introduction to .NET Framework and C#.NET

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;

Component Based Technology


6
Unit-1: Introduction to .NET Framework and C#.NET

                case 3:
                    Console.WriteLine("three");
                    break;
            }
        }
    }
}

Each case represents a value to be checked, followed by a colon, and the statements to get


executed if that case is matched.

The default Case

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;
            }
        }
    }
}

The break Statement

The role of the break statement is to terminate the switch statement.


Without it, execution continues past the matching case statements and falls through to the next
case statements, even when the case labels don’t match the switch variable.

Component Based Technology


7
Unit-1: Introduction to .NET Framework and C#.NET

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

A while loop repeatedly executes a block of code as long as a given condition is true.


For example, the following code displays the numbers 1 through 5:
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 = 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

A do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute


at least one time.
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 a = 0;

Component Based Technology


8
Unit-1: Introduction to .NET Framework and C#.NET

            do {
                Console.WriteLine(a);
                a++;
            } while(a < 5);
        }
    }
}

do-while vs. while


The do-while loop executes the statements at least once, and then tests the condition.
The while loop executes the statement only after testing condition.

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.

The for Loop

A for loop executes a set of statements a specific number of times, and has the syntax:
for ( init; condition; increment ) {
statement(s);
}

A counter is declared once in init.


Next, the condition evaluates the value of the counter and the body of the loop is executed if the
condition is true.
After loop execution, the increment statement updates the counter, also called the loop control
variable.
The condition is again evaluated, and the loop body repeats, only stopping when the condition
becomes false.

For example:

using System;

Component Based Technology


9
Unit-1: Introduction to .NET Framework and C#.NET

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.

Syntax of foreach loop


foreach (element in iterable-item)
{
// body of foreach loop
}
Here iterable-item can be an array or a class of collection.

Component Based Technology


10
Unit-1: Introduction to .NET Framework and C#.NET

var names = new List<string>() { "John", "Tom", "Peter" };


foreach (string name in names)
{
Console.WriteLine(name);
}

John
Tom
Peter

Foreach with Continue

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.

var names = new List<string>() { "John", "Tom", "Peter" };


foreach (string name in names)
{
if (name == "Tom")
{
continue;
}
Console.WriteLine(name);
}

John
Peter

Foreach with Break

If the break statement is used within the loop body, it stops the loop iterations and goes
immediately after the loop body.

var names = new List<string>() { "John", "Tom", "Peter" };

Component Based Technology


11
Unit-1: Introduction to .NET Framework and C#.NET

foreach (string name in names)


{
if (name == "Tom")
{
break;
}
Console.WriteLine(name);
}
Console.WriteLine("OK");

John
OK

Language Integrated Query (LINQ)

Language-Integrated Query (LINQ) is the name for a set of technologies based on


the integration of query capabilities directly into the C# language. Traditionally,
queries against data are expressed as simple strings without type checking at
compile time or IntelliSense support. Furthermore, you have to learn a different
query language for each type of data source: SQL databases, XML documents,
various Web services, and so on. With LINQ, a query is a first-class language
construct, just like classes, methods, events.

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.

// Specify the data source.


int[] scores = { 97, 92, 81, 60 };

// Define the query expression.


IEnumerable<int> scoreQuery =
from score in scores
where score > 80
select score;

// Execute the query.


foreach (int i in scoreQuery)

Component Based Technology


12
Unit-1: Introduction to .NET Framework and C#.NET

{
Console.Write(i + " ");
}

// Output: 97 92 81

Component Based Technology


13

You might also like