Introduction to .
NET
Name: Deepak Gupta
Organization: Chitkara University
Email: [Link]@[Link]
[Link]
Introduction
• .NET provides an environment to develop any
application which can run on Windows.
• .NET is a framework – an API, for programming on
Windows platform.
• .NET emphasize on distributed applications.
S-2 [Link]
Significance of .NET and C#
• Windows Technologies – a process of evolving and
extending the API rather than replacing it. E.g.,
• Windows 3.1
• Windows 95
• Windows XP
• Windows 2003
• Windows Vista
• Windows 7
• COM/DCOM/COM+
S-3 [Link]
Cont…
• Backward compatibility is the success mantra for
evolutionary approach.
• Advantage:
• Existing code does not break completely.
• Disadvantage:
• Complexity
• Better solution:
• Start from scratch.
S-4 [Link]
Cont…
• .NET framework is though a fresh start, but keeps
backward compatibility.
• The communication among Windows software
components happens using COM. So .NET uses
wrappers around existing COM components so that
.NET components can talk to them.
S-5 [Link]
Advantages of .NET
• OO programming.
• Good design.
• Language independence:
All languages in .NET compile to common intermediate
language (IL). Thus, languages are interoperable.
• Better support for dynamic web pages:
Avoids messy ASP code in absence of any OO design, instead
used [Link] (C# and VB2010 can also be used.)
S-6 [Link]
Cont…
• Efficient data access using [Link]
Note: XML allows data manipulation, which can be imported from
and exported to non-Windows platforms.
• Code sharing
• Assemblies are used to share code between applications,
replacing DLLs. Different versions of assemblies can exist side
by side.
• Improved security:
• Assemblies have built in security information which describes
which user (s) or process (s) can call which method on which
class.
S-7 [Link]
Cont…
• Zero impact installation
• Shared assemblies
• Private assemblies (self contained) – No need for registry entries,
just place the files in appropriate folder.
• Support for web services
• VS 2010
S-8 [Link]
Microsoft Intermediate Language (IL)
• .NET compilation process has 2 steps:
• Compilation of source code to Microsoft Intermediate Language
(IL).
• Compilation of IL to platform-specific code (using CLR).
• IL is a low level language and uses numeric codes
rather than text.
• IL can be easily translated into native machine code.
• IL can be compared with Java byte code.
S -9 [Link]
Benefits of IL
• Platform Independence
• The byte code can be put on any platform at runtime (before
CLR does the final compilation).
• The platform independence is not like Java, as it’s is only meant
for Windows (who knows, what’s there in future !).
• Performance Improvement
• JIT (Just-In-Time) compiler compiles only the portion of code
which is called (NOT the complete code).
• Code compiled once is not compiled again when it runs.
• Execution of managed code should be as fast as machine code.
S -10
(Expected !) [Link]
Cont…
• Language Interoperability
• Compile source code written in one language supported by .NET
, say C#, to IL
• Compile source code written in another language supported by
.NET , say [Link], to IL
• Both compiled codes should be interoperable.
S -11 [Link]
First Program
S -12 [Link]
Introduction to C#
• A language of it’s own, generating code which
targets .NET framework.
• A few features of C# (like operator overloading) are
not supported by .NET and vice-versa.
• Case sensitive
• Comments:
• //
• /* */
S -13 [Link]
Cont…
• Using statement is used to locate a namespace
which compiler looks for any class referenced in the
code, but not defined current namespace.
• C# is completely dependent on .NET classes.
• Main () is an entry point and returns either void or
int (Note: C# is case sensitive).
• static is being used as we’re developing an
executable and not a class library.
S -14 [Link]
Compile and Run a Program
• Make sure you use command line of VS2010
(automatically sets environmental variables)
• Compile a program
• csc [Link]
• This will create [Link]
• Finally, run a program by simply running [Link]
S -15 [Link]
Variables
• datatype identifier
• int x; //declaration
• x = 1; //initialization
• int x =1; // declaration and initialization
• Note:
• Prior to variable usage, its initialization is mandatory. This avoids
retrieval of junk values from memory. (Smartness of C# compiler)
S -16 [Link]
Variables Initialization
• C# ensures variables initialization using following
approach:
• class / struct variables are initialized to 0 (by default) as these
cannot be initialized explicitly.
• Local method variables must be initialized explicitly.
public static int Main()
int d;
[Link](d); // Can't do this! Need to initialize d before use
return 0;
S -17 [Link]
Cont…
• MyClass objMyClass
• This creates only a reference for a MyClass object, but you
cannot refer to any method inside object.
• The solution is to instantiate the reference object like:
• objMyClass = new MyClass();
• // This creates a MyClass on the heap.
S -18 [Link]
Type Inference
• Type inference makes use of the var keyword.
• The compiler “infers” what type the variable is by
what the variable is initialized to.
• E.g., var x = 0;
• The compiler identifies that this is a integer variable,
though it’s never declared as integer.
S -19 [Link]
Cont…
• using System;
• namespace Wrox {
• class Program {
static void Main(string[] args) {
var name = "Bugs Bunny";
var age = 25;
var isRabbit = true;
Type nameType = [Link]();
Type ageType = [Link]();
Type isRabbitType = [Link]();
[Link]("name is type " + [Link]());
[Link]("age is type " + [Link]());
[Link]("isRabbit is type " + [Link]());
S -20 • }}} [Link]
Cont…
• Output:
• name is type [Link]
• age is type System.Int32
• isRabbit is type [Link]
• Rules for realizing type interference:
• The variable must be initialized.
• The initializer cannot be null.
• The initializer must be an expression.
S -21 [Link]
Variable Scope
• Rules for finding scope:
• Class / struct scope.
• Block / method scope
• Loop scope (for, while etc.)
• Scope clashes for Local Variable
• Local variables with the same name can’t be declared twice in the same
scope.
• Same variable name can be used in different parts as long as the scope
is different.
S -22 [Link]
Cont…
• public static int Main() {
for (int i = 0; i < 10; i++)
[Link](i);
// i goes out of scope so we can declare a variable i again
for (int i = 9; i >= 0; i--)
[Link](i);
} // i goes out of scope here.
return 0;
• }
S -23 [Link]
Cont…
• What should be output?
public static int Main()
int j = 20;
for (int i = 0; i < 10; i++)
{
// IMP: Can't do this as j is in loop’s scope which is nested into Main() method
// scope.
int j = 30;
[Link](j + i);
}
S -24 [Link]
return 0;
Cont…(Scope clashes for Fields (member) and local
variables
• C# is INTELLIGENT enough to make a distinction between field
and local variables.
using System;
namespace Wrox{
class Scope{
static int j = 20;
public static void Main(){
int j = 30; // Hides class level or field variable
[Link](Scope.j); // Displays class level or field variable
return;
}}}
• NOTE: Use this keyword to access an instance field (a field related to a particular
instance of object.)
S -25 [Link]
Constants
• const int x = 10;
• Constants are:
• Initialized when they are declared.
• Cannot be overwritten.
• Computable at compile time.
• Implicitly static. (means there is no need to include the static
modifier in declaration.)
S -26 [Link]
Cont…
• Advantages:
• Enhance readability:
Programs becomes easier to read by replacing magic numbers and
strings with readable names.
• Single point modification:
Constants make your programs easier to modify.
• Prevent mistakes:
You cannot modify a constant variable by mistake.
S -27 [Link]
Value and Reference Data Types
• Value type stores data directly (uses Stack).
• Reference type stores a reference to the value (uses
managed Heap).
// Two variables - i and j, having different locations
int i, j;
i = 10;
j = i;
S -28 [Link]
Cont…
• Consider a class Vector.
• Assume Vector is a reference type and has an int
member variable called Value.
Vector x, y;
x = new Vector ();
[Link] = 30;
y = x;
[Link] ([Link]);
[Link] = 50;
[Link]([Link]);
S -29 [Link]
Cont…
• Key notes:
• An object is created using new.
• x and y variables are of reference type and both refer to the
same object.
• Changes made to one variable will affect another.
• We don’t use -> to access reference variables. Though behind
the scene, it’s similar to C++ pointers.
• Output:
30
50
S - 30 [Link]
Cont…
• If x = null;
means reference variable y does not refer to an object and
thus it’s not possible to call nonstatic functions or fields.
• C# makes a provision that the primitive types int
and bool belong to value data type category and
larger types (like classes) are put in second
category.
S - 31 [Link]
Predefined Value Types
• The basic data types in C# are not intrinsic to the
language, but are part of the .NET Framework.
• Declaration of an int in C# is like declaration of an
instance of a .NET struct, System.Int32. The advantage
is that you can access class members like:
string s = [Link]();
• No performance issue as types are stored as primitive
types.
S - 32 [Link]
Integer Types
S - 33 [Link]
Cont…
• 8 predefined integers.
• All data types are defined in a platform
independent manner (for possible future porting
of C# and .NET to other platforms).
S - 34 [Link]
Floating Point Types
• double provides twice the precision than float.
• For any non integer number, normally compiler
treat it as a double.
S - 35 [Link]
The Decimal Types
• Higher precision floating – point numbers.
• Useful in financial calculations to have greater
accuracy.
• Slow down the performance.
S - 37 [Link]
The Boolean Types
• Boolean values are either true or false.
• No implicit conversion of a bool into integer or vice
versa.
S - 38 [Link]
The Character Types
• 16-bit characters.
• Enclosed in single quotation mark.
S - 39 [Link]
Predefined Reference Types
• object type is the ultimate parent type from which all
other intrinsic and user-defined types are derived.
S - 40 [Link]
Cont…
• string belongs to reference type.
• One of exception is that the strings are immutable , i.e.,
if you make a change to one string, it’ll create a new
string object and leave another unchanged.
using System;
class StringExample {
public static int Main() {
string s1 = “First String";
string s2 = s1;
[Link]("s1 is " + s1);
[Link]("s2 is " + s2);
s1 = “Second String"; // Creates new string object
[Link]("s1 is now " + s1);
[Link]("s2 is now " + s2);
return 0;
}}
S - 41 [Link]
Cont…
• Output:
First String
First String
Second Sting
First String
S - 42 [Link]
Flow Control
Conditional Statements
• if
• Switch
S - 43 [Link]
The switch Statement
• C#’s switch prohibits fall-through conditions to avoid a lot
of logical errors. The compiler enforces this restriction by
making it mandatory to have break statement in every case
clause.
• One exception to the no-fall-through rule is there when you
can fall through from one case to next if the case is empty.
switch(country)
{
case "india":
case "usa":
case "uk":
language = "English";
break;
}
S - 44 [Link]
Cont…
• In C#:
• The order of the cases doesn’t matter — you can even put the default
case first.
• switch can test a string as the variable.
S - 45 [Link]
Loops
• for
• while
• do-while
• foreach.
• The foreach loop allows you to iterate through each item in a collection,
in one by one mode.
foreach (int value in arrayOfInts)
{
[Link](value);
}
S - 46 [Link]
Cont…
• The value of an item cannot be changed in the collection.
foreach (int value in arrayOfInts)
{
value++; // Cannot do this, compiler will complain.
[Link](value);
}
In such cases, you should make usage of for loop.
S - 47 [Link]
Jump Statements
• The goto statement
goto Label1;
[Link]("This won't be executed");
Label1:
[Link]("Continuing execution from here");
• Restrictions:
• Can’t jump into a block of code such as a for loop.
• Can’t jump out of a class.
S - 48 [Link]
Cont…
• The break statement.
• The continue statement.
• The return statement.
S - 49 [Link]
Enumerations
• An enumeration is a user-defined integer type.
• Set of values with user friendly name.
• Advantages:
• Easier to maintain (values are anticipated / legitimate)
• Enhance readability
• Easier to type (usage of IntelliSense in VS 2010 IDE)
public enum TimeOfDay
{
Morning = 0,
Afternoon = 1,
Evening = 2
}
S - 50 [Link]
Cont…
• How do you access the values?
[Link] will return the value 0.
• In practice, after your code is compiled, enums will exist as
primitive types, just like int and float.
• Enums are instantiated as structs derived from the base
class, [Link]. This means you can call methods
against them to perform some useful tasks without
any performance loss.
TimeOfDay time = [Link];
[Link]([Link]());
S - 51 [Link]
Namespace
• A namespace is a logical rather than physical grouping.
• Defining the namespace hierarchy should be planned out
prior to the start of a project.
• namespace Wrox
• {
• namespace ProCSharp
• {
• namespace Basics
• {
• class NamespaceExample
• {
• // Code for the class here...
• }
• }}}
S - 52 [Link]
Cont…
This can be also written like:
namespace [Link]
{
class NamespaceExample
{
// Code for the class here...
}
}
S - 53 [Link]
Using Directive
using [Link];
using [Link];
S - 54 [Link]
Main () method
• Only one entry point should be there.
• In case, there are two Main () methods. This will give an
error as compiler fails to find the entry point.
o using System;
o namespace Wrox {
o class Client {
o public static int Main() {
o [Link]();
o return 0;
o }}
o class MathExample {
o static int Add(int x, int y) {
o return x + y;
o }
o public static int Main() {
o int i = Add(5,10);
o [Link](i);
o return 0;
o }}}
S - 55 [Link]
Cont…
Better solution:
Specify the entry point using /main switch like
csc [Link] /main:[Link]
[Link] is the name of program file.
S - 56 [Link]
Passing arguments to Main()
• The parameter is a string array, traditionally called args
public static int Main(string[] args)
{
for (int i = 0; i < [Link]; i++)
{
[Link](args[i]);
}
return 0;
}
S - 57 [Link]
Cont…
How do you run the program using command line?
ArgsExample A B C
Output
A
B
C
S - 58 [Link]
C# Programming Guidelines
• Rules for Identifiers.
o They must begin with a letter or underscore, although they can
contain numeric characters.
o You can’t use C# keywords as identifiers.
o In case, you need to use C# keywords as an dentifier (for example, if
you are accessing a class written in a different language), you can
prefix the identifier with the @ symbol to indicate to the compiler
that what follows is to be treated as an identifier (so abstract is not a
valid identifier, but @ abstract is).
• Naming Conventions.
S - 59 [Link]