Introduction to .
NET
Name: Deepak Gupta
Organization: Chitkara University
Email:
[email protected] www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 ASP.NET (C# and VB2010 can also be used.)
S-6 www.chitkara.edu.in
Cont…
• Efficient data access using ADO.NET
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 !) www.chitkara.edu.in
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 VB.NET, to IL
• Both compiled codes should be interoperable.
S -11 www.chitkara.edu.in
First Program
S -12 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
Compile and Run a Program
• Make sure you use command line of VS2010
(automatically sets environmental variables)
• Compile a program
• csc First.cs
• This will create First.exe
• Finally, run a program by simply running First.exe
S -15 www.chitkara.edu.in
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 www.chitkara.edu.in
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;
Console.WriteLine(d); // Can't do this! Need to initialize d before use
return 0;
S -17 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
Cont…
• using System;
• namespace Wrox {
• class Program {
static void Main(string[] args) {
var name = "Bugs Bunny";
var age = 25;
var isRabbit = true;
Type nameType = name.GetType();
Type ageType = age.GetType();
Type isRabbitType = isRabbit.GetType();
Console.WriteLine("name is type " + nameType.ToString());
Console.WriteLine("age is type " + ageType.ToString());
Console.WriteLine("isRabbit is type " + isRabbitType.ToString());
S -20 • }}} www.chitkara.edu.in
Cont…
• Output:
• name is type System.String
• age is type System.Int32
• isRabbit is type System.Bool
• Rules for realizing type interference:
• The variable must be initialized.
• The initializer cannot be null.
• The initializer must be an expression.
S -21 www.chitkara.edu.in
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 www.chitkara.edu.in
Cont…
• public static int Main() {
for (int i = 0; i < 10; i++)
Console.WriteLine(i);
// i goes out of scope so we can declare a variable i again
for (int i = 9; i >= 0; i--)
Console.WriteLine(i);
} // i goes out of scope here.
return 0;
• }
S -23 www.chitkara.edu.in
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;
Console.WriteLine(j + i);
}
S -24 www.chitkara.edu.in
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
Console.WriteLine(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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 ();
x.Value = 30;
y = x;
Console.WriteLine (y.Value);
y.Value = 50;
Console.WriteLine(x.Value);
S -29 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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 = i.ToString();
• No performance issue as types are stored as primitive
types.
S - 32 www.chitkara.edu.in
Integer Types
S - 33 www.chitkara.edu.in
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 www.chitkara.edu.in
Floating Point Types
• double provides twice the precision than float.
• For any non integer number, normally compiler
treat it as a double.
S - 35 www.chitkara.edu.in
The Decimal Types
• Higher precision floating – point numbers.
• Useful in financial calculations to have greater
accuracy.
• Slow down the performance.
S - 37 www.chitkara.edu.in
The Boolean Types
• Boolean values are either true or false.
• No implicit conversion of a bool into integer or vice
versa.
S - 38 www.chitkara.edu.in
The Character Types
• 16-bit characters.
• Enclosed in single quotation mark.
S - 39 www.chitkara.edu.in
Predefined Reference Types
• object type is the ultimate parent type from which all
other intrinsic and user-defined types are derived.
S - 40 www.chitkara.edu.in
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;
Console.WriteLine("s1 is " + s1);
Console.WriteLine("s2 is " + s2);
s1 = “Second String"; // Creates new string object
Console.WriteLine("s1 is now " + s1);
Console.WriteLine("s2 is now " + s2);
return 0;
}}
S - 41 www.chitkara.edu.in
Cont…
• Output:
First String
First String
Second Sting
First String
S - 42 www.chitkara.edu.in
Flow Control
Conditional Statements
• if
• Switch
S - 43 www.chitkara.edu.in
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 www.chitkara.edu.in
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 www.chitkara.edu.in
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)
{
Console.WriteLine(value);
}
S - 46 www.chitkara.edu.in
Cont…
• The value of an item cannot be changed in the collection.
foreach (int value in arrayOfInts)
{
value++; // Cannot do this, compiler will complain.
Console.WriteLine(value);
}
In such cases, you should make usage of for loop.
S - 47 www.chitkara.edu.in
Jump Statements
• The goto statement
goto Label1;
Console.WriteLine("This won't be executed");
Label1:
Console.WriteLine("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 www.chitkara.edu.in
Cont…
• The break statement.
• The continue statement.
• The return statement.
S - 49 www.chitkara.edu.in
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 www.chitkara.edu.in
Cont…
• How do you access the values?
TimeOfDay.Morning 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, System.Enum. This means you can call methods
against them to perform some useful tasks without
any performance loss.
TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());
S - 51 www.chitkara.edu.in
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 www.chitkara.edu.in
Cont…
This can be also written like:
namespace Wrox.ProCSharp.Basics
{
class NamespaceExample
{
// Code for the class here...
}
}
S - 53 www.chitkara.edu.in
Using Directive
using Wrox.ProCSharp.OOP;
using Wrox.ProCSharp.Basics;
S - 54 www.chitkara.edu.in
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 MathExample.Main();
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 Console.WriteLine(i);
o return 0;
o }}}
S - 55 www.chitkara.edu.in
Cont…
Better solution:
Specify the entry point using /main switch like
csc DoubleMain.cs /main:Wrox.MathExample
DoubleMain.cs is the name of program file.
S - 56 www.chitkara.edu.in
Passing arguments to Main()
• The parameter is a string array, traditionally called args
public static int Main(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
}
return 0;
}
S - 57 www.chitkara.edu.in
Cont…
How do you run the program using command line?
ArgsExample A B C
Output
A
B
C
S - 58 www.chitkara.edu.in
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 www.chitkara.edu.in