Page 1

Introduction to .NET Name: Deepak Gupta Organization: Chitkara University Email:

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.


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+

Cont… • Backward compatibility is the success mantra for

evolutionary approach. • Advantage: • Existing code does not break completely.

• Disadvantage: • Complexity • Better solution:

• Start from scratch.


Cont… • .NET framework is though a fresh start, but keeps

backward compatibility. • The





components happens using COM. So .NET uses wrappers around existing COM components so that .NET components can talk to them.


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


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

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


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

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 !)

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

First Program

S -12

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


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

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

Variables • datatype identifier • int x;


• x = 1;


• 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

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

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

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

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 •


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

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

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


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

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

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

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

Value and Reference Data Types â&#x20AC;˘ Value type stores data directly (uses Stack). â&#x20AC;˘ 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

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

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

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

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

Integer Types

S - 33

Cont… • 8 predefined integers. • All








independent manner (for possible future porting of C# and .NET to other platforms).

S - 34

Floating Point Types â&#x20AC;˘ double provides twice the precision than float. â&#x20AC;˘ For any non integer number, normally compiler treat it as a double.

S - 35

The Decimal Types • Higher precision floating – point numbers. • Useful in financial calculations to have greater accuracy. • Slow down the performance.

S - 37

The Boolean Types â&#x20AC;˘ Boolean values are either true or false. â&#x20AC;˘ No implicit conversion of a bool into integer or vice versa.

S - 38

The Character Types â&#x20AC;˘ 16-bit characters. â&#x20AC;˘ Enclosed in single quotation mark.

S - 39

Predefined Reference Types â&#x20AC;˘ object type is the ultimate parent type from which all other intrinsic and user-defined types are derived.

S - 40

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

Cont… • Output: First String First String Second Sting First String

S - 42

Flow Control Conditional Statements • if • Switch

S - 43

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

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

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

Contâ&#x20AC;Ś â&#x20AC;˘ 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

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

Cont… • The break statement. • The continue statement.

• The return statement.

S - 49

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

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

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

S - 52

namespace Wrox { namespace ProCSharp { namespace Basics { class NamespaceExample { // Code for the class here... } }}}

Contâ&#x20AC;Ś This can be also written like: namespace Wrox.ProCSharp.Basics { class NamespaceExample { // Code for the class here... } }

S - 53

Using Directive using Wrox.ProCSharp.OOP; using Wrox.ProCSharp.Basics;

S - 54

Main () method â&#x20AC;˘ Only one entry point should be there. â&#x20AC;˘ In case, there are two Main () methods. This will give an error as compiler fails to find the entry point. o o o o o o o o o o o o o o o o S - 55

using System; namespace Wrox { class Client { public static int Main() { MathExample.Main(); return 0; }} class MathExample { static int Add(int x, int y) { return x + y; } public static int Main() { int i = Add(5,10); Console.WriteLine(i); return 0; }}}

Contâ&#x20AC;Ś 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

Passing arguments to Main() â&#x20AC;˘ 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

Contâ&#x20AC;Ś How do you run the program using command line? ArgsExample A B C

Output A B C

S - 58

C# Programming Guidelines Rules for Identifiers.

â&#x20AC;˘ o

They must begin with a letter or underscore, although they can contain numeric characters.


You canâ&#x20AC;&#x2122;t use C# keywords as identifiers.


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

â&#x20AC;˘ S - 59

Naming Conventions.

Introduction to .NET  

Introduction to .NET and C#, basic concepts, variables, Naming conventions

Read more
Read more
Similar to
Popular now
Just for you