SlideShare a Scribd company logo
2.Getting Started with C#
Getting Started with C#.Net 1
Shoaib Ghachi
Corporate Trainer | SME | Consultant
Microsoft Technology Associate
Agenda
 Introduction to C#.
 Evolution of C#.
 Coding Standards.
 Keyword in C#.
 Data Types in C#
 Dynamic Data Type.
 var Type.
 Value Types and Reference Types.
 What is Variable.
 Region in C#.
 Sample C# Program.
 Operators in C#.
 Constants in C#.
 Type conversion in C#.
 Boxing and Un-Boxing.
Getting Started with C#.Net 2
2.1 Introduction to C#. Net
C# (pronounced as ‘C Sharp’) it’s "simple, modern, general-purpose object-
oriented language."
 It is modern language That combines the power of C++ with productivity
of VB and elegance of Java.
 C# is a modern, type safe programming language, object oriented
language that enables programmers to quickly and easily build solutions for
the Microsoft .NET platform.
 Anders Hejlsberg introduced C# for .Net Framework 1.0. and was
approved by the European Computer Manufacturers Association (ECMA)
and International Standards Organization (ISO).
3
Getting Started with C#.Net
2.2 Evolution of C#
4
Getting Started with C#.Net
C# 1.0 (fx 1.0)
• Classes
• Structs
• Interfaces
• Events
• Properties
• Delegates
• Operators and
expressions
• Statements
• Attributes
C# 2.0 (fx 2.0)
• Generics
• Partial types
• Anonymous
methods
• Nullable value
types
• Iterators
• Covariance and
contravariance
C# 3.0 (fx 3.5)
• Auto-implemented
properties
• Anonymous types
• Query expressions
• Lambda
expressions
• Expression trees
• Extension methods
• Implicitly typed
local variables
• Partial methods
• Object and
collection
initializers
5
Getting Started with C#.Net
C# 4.0 (fx 4.0)
• Dynamic
binding
• Named/optional
arguments
• Generic
covariant and
contravariant
• Embedded
interop types
C# 5.0 (fx 4.5)
• Asynchronous
members
• Caller info
attributes
C# 6.0 (fx 4.6)
• Static imports
• Exception filters
• Auto-property
initializers
• Expression
bodied
members
• Null propagator
• String
interpolation
• nameof
operator
6
Getting Started with C#.Net
C# 7.0 (.Net Core 2.0)
• Out variables
• Tuples and deconstruction
• Pattern matching
• Local functions
• Expanded expression bodied members
• Ref locals and returns
C# 8.0 (.Net Core 3.0)
• Readonly members
• Default interface
methods
• Pattern matching
enhancements
• Using declarations
• Static local functions
• Disposable ref
structs
• Nullable reference
types
• Asynchronous
streams
C# 9.0 (.Net 5.0)
• Records
• Init only setters
• Top-level statements
• Pattern matching
enhancements
• Performance and
interop
• Fit and finish
features
• Support for code
generators
• Module initializers
• New features for
partial methods
2.4 C# Coding Standards
7
Getting Started with C#.Net
Class and Method names should always be in Pascal Case.
Method argument and Local variables should always be in Camel Case.
Avoid the use of underscore while naming identifiers.
Avoid the use of System data types and prefer using the Predefined data
types.
 Always prefix an interface with letter I.
For better code indentation and readability always align the curly braces
vertically.
Always use the using keyword when working with disposable types.It
automatically disposes the object when program flow leaves the scope.
 Always declare the variables as close as possible to their use.
Constants should always be declared in UPPER_CASE.
2.5 Keywords in C#
Contains rich set of 76 reserved keywords. Keywords can be used as
identifiers prefaced by an @.
Keywords Keywords Keywords Keywords
abstract as base bool
Break Byte Case Catch
Char Checked Class Const
Continue Decimal Default Delegate
Do Double Else Enum
Event Explicit Extern False
Finally Fixed Float For
Foreach Goto If Implicit
In Int Interface Internal
Is Lock Long Namespace
New Null Object Operator
Out Override Params Private
Protected Public Readonly Ref 8
Getting Started with C#.Net
Keywords Keywords Keywords Keywords
True Try Typeof Uint
Ulong Unchecked Unsafe Catch
Char Checked Class Const
Using Virtual Void While
9
Getting Started with C#.Net
Some special Keywords:
 typeof is used to find out the managed type of type at run time.
Syntax: Type b1 = typeof(object);
Both 'is' and 'as' keywords are used for type casting in C#.
 is operator is of boolean type whereas as operator is not of
boolean type. The is operator returns true if the given object is of the
same type whereas as operator returns the object when they are
compatible with the given type.
Syntax: a1 is A;
 as operator is used to perform conversion between compatible
reference types or Nullable types. This operator returns the object
when they are compatible with the given type and return null if the
conversion is not possible instead of raising an exception.
Syntax: string s = myObjects[0] as string; 10
Getting Started with C#.Net
2.6 Data Types in C#
Type Description Example
object The base type of all types object obj = null;
string String type - sequence of Unicode
characters
string str = "Mahesh";
bool Boolean type; a bool value is either true or
false
bool val1 = true;
bool val2 = false;
char Character type; a char value is a Unicode
character
char val = 'h';
Most of the data type in C# are taken from C and C++. This tables lists
data types, their description, and a sample example.
11
Getting Started with C#.Net
12
Getting Started with C#.Net
TYPE DESCRIPTION MINIMUM VALUE MAXIMUM VALUE
byte Unsigned byte 0 255
sbyte Signed byte -128 127
short Signed byte -32 768 32 767
ushort Unsigned byte 0 65 535
int Signed byte -2 147 483 648 2 147 483 647
uint Unsigned byte 0 4 294 967 295
long Signed long -9x108 9x108
ulong Unsigned long 0 1,8x1019
Integer Data Types
13
Getting Started with C#.Net
TYPE DESCRIPTION PRECISION
float Single Precision Number 7 digits
double Double Precision Number 15 or 16 digits
decimal Decimal Number 28 or 29 digits
Non-integer Data Types
All non-integer data types are signed.
Arithmetic Overflow
Overflow is an operation that occurs when a calculation produces a result that is
greater in magnitude than that which a given register or storage location can store
or represent.
2.6 Dynamic Data Type
The dynamic keyword brings exciting new features to C# 4.
Dynamic Type means that you can store any type of value in the dynamic
data type variable because type checking for dynamic types of variables takes
place at run-time.
dynamic dynInt = 100;
dynamic dynStr = "Hello";
Getting Started with C#.Net 14
2.7 var Type
•var type is special data type to store varient type of data like an Object type.
•We can store variant type of data into var as well as we can store multiple
values of different type.
static void Main(string[] args)
{
var name = "Welcome";
var a = 34;
Console.WriteLine("name={0} a={1}",name,a);
Console.ReadLine();
}
15
Getting Started with C#.Net
Differences between var and dynamic type:
Getting Started with C#.Net 16
var dynamic
It is introduced in C# 3.0. It is introduced in C# 4.0
The variables are declared using var keyword are
statically typed.
The variables are declared using dynamic keyword
are dynamically typed.
The type of the variable is decided by the compiler
at compile time.
The type of the variable is decided by the compiler
at run time.
Must be initialized.
The variable of this type need not be initialized
Because the compiler does not know the type of
the variable at compile time.
If the variable does not initialized it throw an error.
If the variable does not initialized it will not throw
an error.
It support intelliSense in visual studio. It does not support intelliSense in visual studio
var myvalue = 10; // statement 1
myvalue = “Hello World”; // error
dynamic myvalue = 10; // statement 1
myvalue = “Hello World”; // statement 2
It cannot be used for properties or returning
values from the function. It can only used as a
local variable in function.
It can be used for properties or returning values
from the function
2.8 Types in C#
C# supports two kinds of types: Value Types and Reference Types.
Types Description Types Description
Value Types Includes simple data
types such as int, char,
bool, enums
Value Types Includes simple data
types such as int, char,
bool, enums
Reference Types Includes object, class,
interface, delegate, and
array types
Reference Types Includes object, class,
interface, delegate, and
array types
*Value Types- Value type objects direct contain the actual data in a variables.
With value types, the variables each have their own copy of the data, and it is not possible
for operations on one to affect the other.
int i = 10;
*Reference Types- Reference type variables stores the reference of the actual data.
With reference types, it is possible for two variables to reference the same object, and
thus possible for operations on one variable to affect the object referenced by the other
variable.
MyClass cls1 = new MyClass();
17
Getting Started with C#.Net
Getting Started with C#.Net 18
Value Type Reference Type
All simple types are value types. All Complex Types are Ref. type except struct
Allocate memory at Compile Time. Allocate memory at runtime.
Uses stack to store direct value. Uses memory heap (block of memory) to
store memory address rather than value.
Value type is more faster than Ref. type. Ref. type is portable.
e.g. int, char, bool, enum,stuct. etc. e.g. class, object (system.object), array,
string, delegate etc.
How can we Declare and assign a value to the Variable:
•Declaration:
<type> <variable name>
int a;
string name;
•Assignment/Intialization:
A=10;
Name=“XYZ”;
2.9 What is Variable?
Variable is place holder for values in memory or simply
variable is object of data Type.
19
Getting Started with C#.Net
Using of C# var keyword in LINQ
Getting Started with C#.Net 20
static void Main(string[] args)
{
int[] array = { 1, 2, 4, 6, 8, 9, 11, 14, 15 };
var a = from i in array where i % 2 == 0 select i;
foreach(var _a in a)
{
Console.WriteLine("{0}n",_a);
}
Console.Read();
}
2.10 Region in C#
Console Based program
using System;
using System.Collections;
#region entry point
public class EntryClass
{
public static void Main()
{
NewClass t = new NewClass();
}
}
#endregion entry point
21
Getting Started with C#.Net
2.11 Sample C# program-Console Based program
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("HELLO WORLD");
System.Console.ReadLine();
}
}
}
OUTPUT:
HELLO WORLD 22
Getting Started with C#.Net
2.12 Operators in C#
Operator Function Example
+ addition 11 + 2
- subtraction 11 - 2
* multiplication 11 * 2
/ division 11 / 2
% remainder 11 % 2
++ Increment by 1 ++expr1; expr2++;
-- Decrement by 1 --expr1; expr2--;
*Arithmetic Operators:
23
Getting Started with C#.Net
Operator Function Example
< Less than expr1 < expr2;
> Greater than expr1 > expr2;
<= Less than or equal to expr1 <= expr2;
>= Greater than or equal to expr1 >= expr2;
== Equality expr1 == expr2;
!= Inequality expr1 != expr2;
*Relational Operators
24
Getting Started with C#.Net
Operator Function Example
! Logical NOT ! expr1
|| Logical OR (short circuit) expr1 ||expr2;
&& Logical AND (short circuit) expr1 && expr2;
?: Ternary
cond_expr ? expr1 :
expr2;
* Conditional Operators
The conditional operator takes the following general form:
expr
condition ? execute_if_expr_is_true : execute_if_expr_is_false;
25
Getting Started with C#.Net
2.13 Constants :
Classes and structs can declare constants as members.
Constants are values which are known at compile time and do not
change. Constants are declared as a field, using the const keyword
before the type of the field. Constants must be initialized as they are
declared.
For example:
Multiple constants of the same type can be declared at the
same time, for example:
26
Getting Started with C#.Net
class Calendar2{
static void Main(string[] args)
{
const int months = 12, weeks = 52, days = 365;
const double daysPerWeek = days / weeks;
const double daysPerMonth = days / months;
System.Console.WriteLine(daysPerWeek);
System.Console.WriteLine(daysPerMonth);
System.Console.ReadLine();
}
}
*How To Use Constant?
27
Getting Started with C#.Net
2.14 Type Conversion:
There are two types of type conversion implicit and explicit.
Implicit: Automatic compiler conversion where data loss is not an issue.
e.g. int iVal = 34;
long lVal = iVal;
Explicit: A conversion where data loss may happen and is recommended that the
programmer writes additional processing
e.g. long lVal = 123456;
int iVal = (int) lVal;
28
Getting Started with C#.Net
* C# Implicit Conversion:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 2;
double y = 12.2;
double z;
z = x + y; //x is automatically converted into a double
Console.WriteLine(z);
Console.Read();
}
}
} 29
Getting Started with C#.Net
* C# Explicit Conversion:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double x = 2.1;
int y = 12;
int z = (int)x + y; //Explicit conversion from double to int
Console.WriteLine(z);
Console.Read();
}
}
} 30
Getting Started with C#.Net
* Conversion by Convert Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int y;
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(y);
Console.Read();
}
}
}
31
Getting Started with C#.Net
* Conversion by Convert Class:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
double lVal = 123.45;
int iVal = Convert.ToInt32(lVal); //double is converted to int
Console.WriteLine(iVal);
Console.Read();
}
}
}
32
Getting Started with C#.Net
Int.Parse, Convert.ToInt32 and int.TryParse
Getting Started with C#.Net 33
int.Parse Convert.ToInt32 int.TryParse
int.Parse(string s)
Convert.ToInt32(bo
ol value)
int.TryParse (string s,out
int result)
string str = "20"; 20 20 20
string str = null; ArgumentNullException 0
Failed to Convert but
returns 0 and doesn't
throw the exception
string str = “abc"; FormatException FormatException
Failed to Convert but
returns 0 and doesn't
throw the exception
string str =
“55555574545545
45454545";
OverflowException OverflowException
Failed to Convert but
returns 0 and doesn't
throw the exception
bool b = false; Not Supporting to convert 0
Failed to Convert but
returns 0 and doesn't
throw an Exception
Getting Started with C#.Net 34
Getting Started with C#.Net 35
2.15 Boxing And UnBoxing
Object (System.Object) is the ultimate base class for all types.
Any type can be upcast to object.System.Object is such an important class that
C# provides the object keyword as an alias for System.Object.
Boxing: To cast Value type to Object Type This process is known as “Boxing”.
static void Main(string[] args)
{
int i = 30;
Object MyObj = i;
Console.WriteLine(MyObj);
Console.ReadLine();
}
36
Getting Started with C#.Net
Unboxing: To cast Object type to Value Type This process is known as “Unboxing”.
static void Main(string[] args)
{
Object MyObj = 30;
int i = (int)MyObj;
Console.WriteLine(i);
Console.ReadLine();
}
37
Getting Started with C#.Net

More Related Content

2.Getting Started with C#.Net-(C#)

  • 1. 2.Getting Started with C# Getting Started with C#.Net 1 Shoaib Ghachi Corporate Trainer | SME | Consultant Microsoft Technology Associate
  • 2. Agenda  Introduction to C#.  Evolution of C#.  Coding Standards.  Keyword in C#.  Data Types in C#  Dynamic Data Type.  var Type.  Value Types and Reference Types.  What is Variable.  Region in C#.  Sample C# Program.  Operators in C#.  Constants in C#.  Type conversion in C#.  Boxing and Un-Boxing. Getting Started with C#.Net 2
  • 3. 2.1 Introduction to C#. Net C# (pronounced as ‘C Sharp’) it’s "simple, modern, general-purpose object- oriented language."  It is modern language That combines the power of C++ with productivity of VB and elegance of Java.  C# is a modern, type safe programming language, object oriented language that enables programmers to quickly and easily build solutions for the Microsoft .NET platform.  Anders Hejlsberg introduced C# for .Net Framework 1.0. and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). 3 Getting Started with C#.Net
  • 4. 2.2 Evolution of C# 4 Getting Started with C#.Net C# 1.0 (fx 1.0) • Classes • Structs • Interfaces • Events • Properties • Delegates • Operators and expressions • Statements • Attributes C# 2.0 (fx 2.0) • Generics • Partial types • Anonymous methods • Nullable value types • Iterators • Covariance and contravariance C# 3.0 (fx 3.5) • Auto-implemented properties • Anonymous types • Query expressions • Lambda expressions • Expression trees • Extension methods • Implicitly typed local variables • Partial methods • Object and collection initializers
  • 5. 5 Getting Started with C#.Net C# 4.0 (fx 4.0) • Dynamic binding • Named/optional arguments • Generic covariant and contravariant • Embedded interop types C# 5.0 (fx 4.5) • Asynchronous members • Caller info attributes C# 6.0 (fx 4.6) • Static imports • Exception filters • Auto-property initializers • Expression bodied members • Null propagator • String interpolation • nameof operator
  • 6. 6 Getting Started with C#.Net C# 7.0 (.Net Core 2.0) • Out variables • Tuples and deconstruction • Pattern matching • Local functions • Expanded expression bodied members • Ref locals and returns C# 8.0 (.Net Core 3.0) • Readonly members • Default interface methods • Pattern matching enhancements • Using declarations • Static local functions • Disposable ref structs • Nullable reference types • Asynchronous streams C# 9.0 (.Net 5.0) • Records • Init only setters • Top-level statements • Pattern matching enhancements • Performance and interop • Fit and finish features • Support for code generators • Module initializers • New features for partial methods
  • 7. 2.4 C# Coding Standards 7 Getting Started with C#.Net Class and Method names should always be in Pascal Case. Method argument and Local variables should always be in Camel Case. Avoid the use of underscore while naming identifiers. Avoid the use of System data types and prefer using the Predefined data types.  Always prefix an interface with letter I. For better code indentation and readability always align the curly braces vertically. Always use the using keyword when working with disposable types.It automatically disposes the object when program flow leaves the scope.  Always declare the variables as close as possible to their use. Constants should always be declared in UPPER_CASE.
  • 8. 2.5 Keywords in C# Contains rich set of 76 reserved keywords. Keywords can be used as identifiers prefaced by an @. Keywords Keywords Keywords Keywords abstract as base bool Break Byte Case Catch Char Checked Class Const Continue Decimal Default Delegate Do Double Else Enum Event Explicit Extern False Finally Fixed Float For Foreach Goto If Implicit In Int Interface Internal Is Lock Long Namespace New Null Object Operator Out Override Params Private Protected Public Readonly Ref 8 Getting Started with C#.Net
  • 9. Keywords Keywords Keywords Keywords True Try Typeof Uint Ulong Unchecked Unsafe Catch Char Checked Class Const Using Virtual Void While 9 Getting Started with C#.Net
  • 10. Some special Keywords:  typeof is used to find out the managed type of type at run time. Syntax: Type b1 = typeof(object); Both 'is' and 'as' keywords are used for type casting in C#.  is operator is of boolean type whereas as operator is not of boolean type. The is operator returns true if the given object is of the same type whereas as operator returns the object when they are compatible with the given type. Syntax: a1 is A;  as operator is used to perform conversion between compatible reference types or Nullable types. This operator returns the object when they are compatible with the given type and return null if the conversion is not possible instead of raising an exception. Syntax: string s = myObjects[0] as string; 10 Getting Started with C#.Net
  • 11. 2.6 Data Types in C# Type Description Example object The base type of all types object obj = null; string String type - sequence of Unicode characters string str = "Mahesh"; bool Boolean type; a bool value is either true or false bool val1 = true; bool val2 = false; char Character type; a char value is a Unicode character char val = 'h'; Most of the data type in C# are taken from C and C++. This tables lists data types, their description, and a sample example. 11 Getting Started with C#.Net
  • 12. 12 Getting Started with C#.Net TYPE DESCRIPTION MINIMUM VALUE MAXIMUM VALUE byte Unsigned byte 0 255 sbyte Signed byte -128 127 short Signed byte -32 768 32 767 ushort Unsigned byte 0 65 535 int Signed byte -2 147 483 648 2 147 483 647 uint Unsigned byte 0 4 294 967 295 long Signed long -9x108 9x108 ulong Unsigned long 0 1,8x1019 Integer Data Types
  • 13. 13 Getting Started with C#.Net TYPE DESCRIPTION PRECISION float Single Precision Number 7 digits double Double Precision Number 15 or 16 digits decimal Decimal Number 28 or 29 digits Non-integer Data Types All non-integer data types are signed. Arithmetic Overflow Overflow is an operation that occurs when a calculation produces a result that is greater in magnitude than that which a given register or storage location can store or represent.
  • 14. 2.6 Dynamic Data Type The dynamic keyword brings exciting new features to C# 4. Dynamic Type means that you can store any type of value in the dynamic data type variable because type checking for dynamic types of variables takes place at run-time. dynamic dynInt = 100; dynamic dynStr = "Hello"; Getting Started with C#.Net 14
  • 15. 2.7 var Type •var type is special data type to store varient type of data like an Object type. •We can store variant type of data into var as well as we can store multiple values of different type. static void Main(string[] args) { var name = "Welcome"; var a = 34; Console.WriteLine("name={0} a={1}",name,a); Console.ReadLine(); } 15 Getting Started with C#.Net
  • 16. Differences between var and dynamic type: Getting Started with C#.Net 16 var dynamic It is introduced in C# 3.0. It is introduced in C# 4.0 The variables are declared using var keyword are statically typed. The variables are declared using dynamic keyword are dynamically typed. The type of the variable is decided by the compiler at compile time. The type of the variable is decided by the compiler at run time. Must be initialized. The variable of this type need not be initialized Because the compiler does not know the type of the variable at compile time. If the variable does not initialized it throw an error. If the variable does not initialized it will not throw an error. It support intelliSense in visual studio. It does not support intelliSense in visual studio var myvalue = 10; // statement 1 myvalue = “Hello World”; // error dynamic myvalue = 10; // statement 1 myvalue = “Hello World”; // statement 2 It cannot be used for properties or returning values from the function. It can only used as a local variable in function. It can be used for properties or returning values from the function
  • 17. 2.8 Types in C# C# supports two kinds of types: Value Types and Reference Types. Types Description Types Description Value Types Includes simple data types such as int, char, bool, enums Value Types Includes simple data types such as int, char, bool, enums Reference Types Includes object, class, interface, delegate, and array types Reference Types Includes object, class, interface, delegate, and array types *Value Types- Value type objects direct contain the actual data in a variables. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. int i = 10; *Reference Types- Reference type variables stores the reference of the actual data. With reference types, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. MyClass cls1 = new MyClass(); 17 Getting Started with C#.Net
  • 18. Getting Started with C#.Net 18 Value Type Reference Type All simple types are value types. All Complex Types are Ref. type except struct Allocate memory at Compile Time. Allocate memory at runtime. Uses stack to store direct value. Uses memory heap (block of memory) to store memory address rather than value. Value type is more faster than Ref. type. Ref. type is portable. e.g. int, char, bool, enum,stuct. etc. e.g. class, object (system.object), array, string, delegate etc.
  • 19. How can we Declare and assign a value to the Variable: •Declaration: <type> <variable name> int a; string name; •Assignment/Intialization: A=10; Name=“XYZ”; 2.9 What is Variable? Variable is place holder for values in memory or simply variable is object of data Type. 19 Getting Started with C#.Net
  • 20. Using of C# var keyword in LINQ Getting Started with C#.Net 20 static void Main(string[] args) { int[] array = { 1, 2, 4, 6, 8, 9, 11, 14, 15 }; var a = from i in array where i % 2 == 0 select i; foreach(var _a in a) { Console.WriteLine("{0}n",_a); } Console.Read(); }
  • 21. 2.10 Region in C# Console Based program using System; using System.Collections; #region entry point public class EntryClass { public static void Main() { NewClass t = new NewClass(); } } #endregion entry point 21 Getting Started with C#.Net
  • 22. 2.11 Sample C# program-Console Based program using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { System.Console.WriteLine("HELLO WORLD"); System.Console.ReadLine(); } } } OUTPUT: HELLO WORLD 22 Getting Started with C#.Net
  • 23. 2.12 Operators in C# Operator Function Example + addition 11 + 2 - subtraction 11 - 2 * multiplication 11 * 2 / division 11 / 2 % remainder 11 % 2 ++ Increment by 1 ++expr1; expr2++; -- Decrement by 1 --expr1; expr2--; *Arithmetic Operators: 23 Getting Started with C#.Net
  • 24. Operator Function Example < Less than expr1 < expr2; > Greater than expr1 > expr2; <= Less than or equal to expr1 <= expr2; >= Greater than or equal to expr1 >= expr2; == Equality expr1 == expr2; != Inequality expr1 != expr2; *Relational Operators 24 Getting Started with C#.Net
  • 25. Operator Function Example ! Logical NOT ! expr1 || Logical OR (short circuit) expr1 ||expr2; && Logical AND (short circuit) expr1 && expr2; ?: Ternary cond_expr ? expr1 : expr2; * Conditional Operators The conditional operator takes the following general form: expr condition ? execute_if_expr_is_true : execute_if_expr_is_false; 25 Getting Started with C#.Net
  • 26. 2.13 Constants : Classes and structs can declare constants as members. Constants are values which are known at compile time and do not change. Constants are declared as a field, using the const keyword before the type of the field. Constants must be initialized as they are declared. For example: Multiple constants of the same type can be declared at the same time, for example: 26 Getting Started with C#.Net
  • 27. class Calendar2{ static void Main(string[] args) { const int months = 12, weeks = 52, days = 365; const double daysPerWeek = days / weeks; const double daysPerMonth = days / months; System.Console.WriteLine(daysPerWeek); System.Console.WriteLine(daysPerMonth); System.Console.ReadLine(); } } *How To Use Constant? 27 Getting Started with C#.Net
  • 28. 2.14 Type Conversion: There are two types of type conversion implicit and explicit. Implicit: Automatic compiler conversion where data loss is not an issue. e.g. int iVal = 34; long lVal = iVal; Explicit: A conversion where data loss may happen and is recommended that the programmer writes additional processing e.g. long lVal = 123456; int iVal = (int) lVal; 28 Getting Started with C#.Net
  • 29. * C# Implicit Conversion: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int x = 2; double y = 12.2; double z; z = x + y; //x is automatically converted into a double Console.WriteLine(z); Console.Read(); } } } 29 Getting Started with C#.Net
  • 30. * C# Explicit Conversion: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { double x = 2.1; int y = 12; int z = (int)x + y; //Explicit conversion from double to int Console.WriteLine(z); Console.Read(); } } } 30 Getting Started with C#.Net
  • 31. * Conversion by Convert Class: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int y; y = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(y); Console.Read(); } } } 31 Getting Started with C#.Net
  • 32. * Conversion by Convert Class: using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { double lVal = 123.45; int iVal = Convert.ToInt32(lVal); //double is converted to int Console.WriteLine(iVal); Console.Read(); } } } 32 Getting Started with C#.Net
  • 33. Int.Parse, Convert.ToInt32 and int.TryParse Getting Started with C#.Net 33 int.Parse Convert.ToInt32 int.TryParse int.Parse(string s) Convert.ToInt32(bo ol value) int.TryParse (string s,out int result) string str = "20"; 20 20 20 string str = null; ArgumentNullException 0 Failed to Convert but returns 0 and doesn't throw the exception string str = “abc"; FormatException FormatException Failed to Convert but returns 0 and doesn't throw the exception string str = “55555574545545 45454545"; OverflowException OverflowException Failed to Convert but returns 0 and doesn't throw the exception bool b = false; Not Supporting to convert 0 Failed to Convert but returns 0 and doesn't throw an Exception
  • 34. Getting Started with C#.Net 34
  • 35. Getting Started with C#.Net 35
  • 36. 2.15 Boxing And UnBoxing Object (System.Object) is the ultimate base class for all types. Any type can be upcast to object.System.Object is such an important class that C# provides the object keyword as an alias for System.Object. Boxing: To cast Value type to Object Type This process is known as “Boxing”. static void Main(string[] args) { int i = 30; Object MyObj = i; Console.WriteLine(MyObj); Console.ReadLine(); } 36 Getting Started with C#.Net
  • 37. Unboxing: To cast Object type to Value Type This process is known as “Unboxing”. static void Main(string[] args) { Object MyObj = 30; int i = (int)MyObj; Console.WriteLine(i); Console.ReadLine(); } 37 Getting Started with C#.Net