• No results found

Windows

N/A
N/A
Protected

Academic year: 2021

Share "Windows"

Copied!
113
0
0

Loading.... (view fulltext now)

Full text

(1)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

According to Microsoft .Net is a platform built on open internet protocols & standards with tools and services that meld computing and communication in new ways

It’s an environment for developing and running software applications featuring ease of development of web based services, rich standard runtime services available to components written in variety of programming languages & provides inter language & inter machine inoperability

The .NET Framework is a new computing platform that simplifies application development in the highly distributed environment of the Internet. The .NET Framework is designed to fulfill the following objectives:

• Preserve consistency between objects that are stored and executed locally, objects that are Internet-distributed but are executed locally, and objects that are stored and executed remotely on a server.

• Avoid deployment and versioning conflicts. No DLL update upon deployment. Solves the DLL Hell Syndrome.

• Guarantee safe execution of code, even if written by unknown semi-trusted third party. Avoid the slowness of scripted or interpreted languages.

• Preserve development environment consistency between windows-based applications and web-based applications.

The .NET framework includes two main components: 1. The .NET Class library

2. The Common Language Runtime.

.NET Base Class Libraries (also called as Framework Class Libraries (FCL)

The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face. Most of the types presented by the .NET base class library are fully extensible, allowing you to build types that incorporate your own functionality into your managed code. These class libraries are distributed with MS.NET Framework and works with any language under the common language runtime environment. Therefore if you are familiar with one .NET language then you can easily migrate to other .NET Languages

All the base class libraries are grouped under the root namespace System.

Namespace: A namespace is a logical collection of classes and other types with unique name. The structure of the namespace is like a tree where all the related classes are like leaves.

The most important namespaces in the .NET class library are: • System • System.IO • System.Collections • System.Threading • System.Reflection • System.Security • System.Net • System.Data • System.XML • System.Web • System.Web.Services • System.Windows.Forms • System.Drawing • System.Globalization • System.Resources

(2)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

CLR (COMMON LANGUAGE RUNTIME)

CLR is the foundation of .NET Framework. The common Language Runtime manages code at execution time. It does Memory management, thread management, and runs the code on different platforms (Client or Server). It enforces strict variable type definitions, security, and robustness.

CLR provides the following benefits for the application developers: • Vastly simplified development.

• Seamless integration of the code written in various languages. • Evidence-based security with code identity.

• Assembly-based deployment that eliminates DLL Hell. • Side-by-side versioning of reusable components. • Code reuse through implementation inheritance. • Automatic object lifetime management.

• Self describing objects.

CLR is a component divided in sub components which perform their own respective tasks. CLR as the name specifies provides a common runtime environment for different languages like VC++, C#, VB.NET, J# and JavaScript. The code written in these languages is compiled with their respective language compliers to give a common intermediate language called MSIL (Microsoft Intermediate Language) and Metadata. This files generated are called as PE (Portable Executable).

The CLR is a multi-language execution environment

MS Intermediate Language: MSIL is an intermediate instruction set which is processor and hardware independent. The source code when compiled gives MSIL which is an input to the operating system and with the help of CLR is converted into native code which is processor specific.

Microsoft supply a tool called Ildasm, which can be used to view the metadata and IL for an assembly. Source code can be reverse-engineered from IL, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

You can write IL programs directly, for example: .assembly MyAssembly {}

.class MyApp {

.method static void Main() {

.entrypoint ldstr Hello, IL!"

call void System.Console::WriteLine(class System.Object) ret

} }

(3)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

Portable Executable (PE) is a Microsoft Win32 compatible format file for .Net applications which contains the MSIL code and Metadata in binary form. It has the extension .exe or .dll. PE has COFF (Common Object File Format) specification.

Metadata: Metadata is the information that describes every element managed by the runtime i.e. an assembly, a loadable file, type, methods etc. This can also include information required for debugging and garbage collection, security attributes, marshalling data, extended classes and member definitions, version binding etc.

To enable the runtime to provide services to managed code, language compilers must emit metadata that describes the types, members, and references in your code. Metadata is stored with Code; every loadable common Language runtime Portable Executable (PE) file contains metadata. The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set run-time context boundaries.

What is Type safety?

Defining the data types in a language to be specific and strict in their behaviour.

Datatypes are different in different languages and hence cannot be compiled with a single compiler. In .net languages CLR takes the responsibility of verifying the typesafety of the code being executed both at compile time and runtime. Hence the code is Managed.

CTS (COMMON TYPE SYSTEM)

CTS is the main component of the CLR. It is a specification where different datatypes are defined. This .net datatype collection is used by the language compilers to map the language datatypes to datatypes defined in CTS. This ensures the interoperability at runtime as the code written in one language when invoked from another language would not be misinterpret the data because the calling language datatypes would map the same CTS datatypes to which the called language datatypes are mapped.

CTS provide a framework for cross-language integration and address a number of issues:

• Similar but subtly different, types (for example, Integer is 16 bits in VB6, but int in C++ is 32 bits; strings in VB6 are represented as BSTRs and in C++ as char pointers or a string class of some sort; and so on)

• Limited code reuse(for example, you can’t define a new type in one language and impart into another language) • Inconsistent object models.

For example, an integer variable in C# is written as int, whereas in Visual Basic it is written as integer. Therefore in .Net Framework you have single type called System.Int32 to interpret these variables. Similarly, for the ArrayList datatype .Net framework has a common type called System.Collections.ArrayList. In .Net Framework, System.Object is the common base type from where all the other types are derived.

(4)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

COMMON LANGUAGE SPECIFICATION

CLS = Common Language Specification. This is a subset of the CTS, which all .NET languages are expected to support. The idea is that any program, which uses CLS-compliant types, can interoperate with any .NET program written in any language. The CLS is a set of constructs and constraints that serves as a guide for library writers and compiler writers. It allows libraries to be fully usable from any language supporting the CLS, and for those languages to integrate with each other. The CLS is a subset of the CTS. The CTS is also important to application developers who are writing code that will be used by other developers. When developers design publicly accessible APIs following the rules of the CLS, those APIs are easily used from all other programming languages that target the common language runtime.

In short, this allows very tight interoperability between different .NET languages, for example allowing a C# class to inherit from a VB class.

NOTE: CLS is not a part of CLR Specification. Few .NET Framework Supported Languages:

APL, C++, C#, COBOL, Component Pascal, Curriculum, Eiffel, Forth, Fortran, Haskell, Java Language, Microsoft Jscript, Mercury, Mondrian, Oberon, Oz, Pascal, Perl, Python, RPG, Scheme, Small Talk, Standard Ml, Microsoft Visual Basic. JIT (JUST IN TIME COMPILER)

JIT compiler compiles the managed or MSIL code into native code. JIT compiles only the required code for execution i.e. as the code is being visited for execution and also the compiled code is cached so that if the block of code is called again the same cached copy is directly executed. Advantage of managed code being compiled in small required fractions is processor time.

There are three types of JIT compilers • Standard JIT

• Econo JIT = Standard JIT – Caching (this is ideal for small devices) • Pre JIT

Standard JIT: This compiles a block of code as it is visited for execution. The compiled code is cached so that the subsequent call to the same block of code is directly reused.

Pre JIT: was planned in the initial draft of .NET but was never supported instead Microsoft provided a utility program called NGen.exe (Native Generator) the complete MSIL code is compiled to native code for that machine and is stored in GAC (GLOBAL ASSEMBLY CACHE) The advantage being the first time execution is also very fast because its already in precompiled form, but the output of the NGen is not portable and is always machine dependent.

Note: we don’t have any facility to set our choice of JIT. For desktops Standard JIT is used and for Compact devices Econo JIT is used.

Garbage Collection

The variables in the application can be allocated memory either in Global memory or Stack memory or Heap memory. All global variables are allocated memory when the program starts execution and would remain in memory for the lifetime of the application.

All local variables and parameters of a function are allocated memory when the function is called and they are deallocated memory automatically when the function returns.

Heap memory is used for all dynamic memory requirements i.e. variables like pointers for which until runtime we don’t know the amount of memory required would be allocated memory from the heap. But the size of heap is limited and all allocations done on heap must be also deallocated when that pointer doesn’t need the memory anymore. The deallocated heap memory then can be used for another pointer dynamic memory allocation.

Memory Leakage: If some pointers are allocated memory on the heap and are never deallocated from the heap before the pointer itself goes out of scope then such memory can never be freed and would remain as Leakage from the heap as it cannot be allocated to another pointer.

In .Net the memory de-allocation in .Net is handled by Garbage Collector. It gets activated when the heap is full and there is a need for release of memory.

(5)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

unreferenced objects (objects which are no longer in use). When garbage collector is initiated all other threads running within the application are temporarily suspended and hence the sooner the garbage collector finishes its job the better would be the performance of the application.

To optimize the work of garbage collector Microsoft has divided the heap memory into three equal parts called Generations: GEN0, GEN1, and GEN2. This is compact garbage collection. New objects are always created in GEN0 and are promoted to other generations based on their lifespan. Long lived objects would be destroyed last as these objects would move from GEN0 to GEN1 and from GEN1 to GEN2.

Note: In .net the address of object can changes at runtime as it goes from one generation to another.

In .Net the object once created are never guaranteed to be destroyed because they might get promoted to higher generations and GC would not visit those generations as memory is mostly available in lower generations itself.

Security Manager

Security manager is a component in CLR.

There are three types of security models supported in .Net. • Code Access Security(CAS)

• Role Based Security

• Asp .Net Web Application Security.

Code Access Security

CAS determines whether or not a piece of code is allowed to run and also what resources to use. For example, CAS will prevent malicious code from entering your system and causing havoc.

It is an integrated security model that grants permission to resources based on evidence and the evidence may include 1. From where the assembly is being loaded.

2. If downloaded from web what is the URL of the source directory? 3. What is the Strong Name

4. Who is the publisher, if digitally signed?

The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group and each code group is granted the permissions specified in a named permission set. An example: Using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group which complies with the permissions defined by the 'Internet' named permission set.

Microsoft defines some default policies but you can modify these and even create your own. To view the code groups defined on your system; Run 'caspol' from the command-line and checkout the different options on display

When a program code is using another code from another machine the security manager in CLR is responsible for managing the implementation of CAS based on the identity or evidence of that machine from which the code is being used.

Class Loader

It is a sub component in CLR and is responsible for loading classes and other types as and when needed .It also loads the PE if it’s not already loaded.

Assemblies:

Assemblies are building blocks of .Net framework applications. They form the fundamental unit of code execution, deployment, version control, reusability, activation scoping and security permissions. It can be made of one file or made of multiple files

An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there is one master module containing the manifest while other assemblies exist as non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the most interesting and extremely useful areas of .NET architecture along with

reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics Assemblies are self-describing by means of their manifest, which is an integral part of every assembly.

The manifest: (also called as Assembly Metadata)

• Establishes the assembly identity (in the form of a text name), version, culture, and digital signature (if the assembly is to be shared across applications).

(6)

Deccansoft Software Services – MS.NET

Overview of .NET Framework

• Specifies the types and resources that make up the assembly, including which are exported from the assembly. • Itemizes the compile-time dependencies on other assemblies.

• Specifies the set of security permissions required for the assembly to run properly.

This information is used at run time to resolve references, enforce version-binding policy, and validate the integrity of loaded assemblies. The runtime can determine and locate the assembly for any running object, since every type is loaded in the context of an assembly. Assemblies are also the unit at which code access security permissions are applied. The identity evidence for each assembly is considered separately when determining what permissions to grant the code it contains. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. Types of Assemblies

Private Assembly: An assembly which is present in the same directory as the exe with every application refining to it. Shared Assembly: A single copy of it is in GAC and is shared by all the applications referring to that assembly.

Satellite Assembly: A resource only assembly for a given culture. We can have more than one satellite assembly for one application.

Assembly Manifest

(Meta Data)

Type Meta Data

MSIL

Resources

.NET Module contains

1. Type Meta Data

2. MSIL

Resource

DLL

Managed code: by managed code, it means that the complete life cycle and execution is managed by the .NET Common Language Runtime (CLR). The .NET CLR manages the memory on behalf of the managed code, performs garbage collection on the managed heap, perform assembly validation and assembly (component) resolution on behalf of the program. The CLR also maintains the security constraints applied to the managed code.

Note: By un-safe code, it means that the managed program can access the memory address using pointers. There are two points to remember here

• Un-safe code is different from un-managed as it is still managed by the CLR • You still can not perform pointer arithmetic in un-safe code.

Un-managed code runs outside the CLR control while the unsafe code runs inside the CLR’s control. Both safe and un-managed codes may use pointers and direct memory addresses.

(7)

Deccansoft Software Services

Console- Main

• Solution is a Collection of Projects. One Solution can have many projects and each project can be of

different language. This file has the extension .sln.

• A Project is a collection of files including Source Code (.vb/.cs), Resources(.resx), Configuration(.config) files etc…The project file has the extension .vbproj or .csproj • A project when build (Compilation + Linking) generates a EXE/DLL as output. Module Module1 Sub Main() Console.WriteLine("Module1") End Sub End Module Commandline Arguments:

The best way of providing input to the commandline application is using commandline arguments. Module Module1

Sub Main(ByVal args As String())

Console.WriteLine("Hello " & args(0)) End Sub

End Module

args is the commandline arguments.

View Æ Solution Explorer Æ Project Æ Right Click Æ Properties Æ Debug Tab Æ Command Line Arguments Æ Provide string separated by space

Return value of Main: Module Module1

Function Main(ByVal args() As String) as Integer Console.WriteLine("Hello " & args(0)) Return 0

End Function End Module

The return value of Main is used by the current application to communicate its state to the parent process when it terminates. The Interger return value can be predefined with some meaning and same will be used by the parent process to know the state of child process terminated. This return value of an application is called as EXIT CODE.

Multiple Modules in One Project

One Project can have multiple modules but only one of many module with valid Main can be treated as Startup or entry point.

Module Module2 Sub Main()

Console.WriteLine("Module2") End Sub

End Module

To Set Startup Object:View Æ Solution Explorer Æ Project Æ Right Click Æ Properties Æ Application Tab Æ Starup Object Æ Select Module whose Main should be used as entry point.

Every Module in the project can be placed in same file or in different files. In either case the compiler is going to compile together.

To Add another File with Module to Project: Goto Solution Explorer Æ Right Click on Project Æ Add ÆModule

Following are the possible forms of Main which can be used in a module so that the module can be marked as startup object. If Main is written in Class it must be marked as Shared.

Module Module1 Sub Main()

Console.WriteLine("Module1") End Sub

Sub Main(ByVal args As String())

Console.WriteLine("Hello " & args(0)) End Sub

Function Main() As Integer Console.WriteLine("Hello") Return 0

End Function

Class Class1

Shared Sub Main()

Console.WriteLine("Module1") End Sub

Shared Sub Main(ByVal args As String()) Console.WriteLine("Hello " & args(0)) End Sub

Shared Function Main() As Integer Console.WriteLine("Hello")

Return 0 End Function

(8)

Deccansoft Software Services

Console- Main

as Integer.

Console.WriteLine("Hello " & args(0)) Return 0

End Function End Module

as Integer. Console.WriteLine("Hello " & args(0)) Return 0

End Function End Class

As an Object Oriented programmer its always better to avoid usage of Module in a project. This is because every member of a module is by default treated as Global Member and it has free access through out the project and this is against object orientation principles

(9)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Integral Types

DataType Size . Net (CTS) Comments

Byte 1 System.Byte 0 - 255 It is Unsigned SByte 1 System.SByte -128 to 127 - Signed

Short 2 System.Int16 Signed short

UShort 2 System.UInt16 Unsigned short

Integer 4 System.Int32 Range For

n – bits signed numbers: -2n-1 to 2n-1 - 1 n-bits unsigned numbers = 0 to 2n - 1 UInteger 4 System.Unt32

Long 8 System.Int64

ULong 8 System.UInt64

Floating Types

Decimal 16 System.Decimal Has up to 28 digits after decimal Single 4 System.Single Has up to 8 digits after decimal Double 8 System.Double Has up to 15 digits after decimal Other DataTypes

Char 2 System.Char Uses Unicode Charset

String * 4 Systring.String Uses Unicode Charset Boolean 2 System.Boolean True / False

Object * System.Object Generic Datatype

Date 8 System.DateTime

All the above datatypes are ValueTypes but String and Object are Reference Types. Value Types directly hold the value-

All Basic Types, Structures & Enum

Reference Types hold the reference to the value – Sring, Object, Class, Arrays, Delegates

ValueType

Var = Value

Heap Mem

Var

Value

Ref type

Variable Declaration Syntax: Dim var1, var2 as <DataType> Dim n1, n2 as Integer.

Dim n1 as Integer = 10

Dim n1, n2 as Integer = 10 ‘ Invalid

Dim n1 as Integer = 10, n2 as Integer = 10 ‘Valid

• Based on datatype every variable declared is set to default value

• A variable declared in a block is local to the block in which it is declared

• A variable declared in outer block cannot be re-declared in the inner block.

If “Option Explicit Off” is mentioned then we don’t need to declare the variable and by default it is treated to be of type “Object”

But if “Option Explicit On” is mentioned then every variable used must be declared otherwise it gives compilation error. Literal Constants

I – Integer, L – Long, D – Decimal, F – Single, R – Double, C – Char Example: 10L is Long, “A” is String, “A”c is Char.

Alternate Variable Declaration Syntax:

% - Interger, & - Long, @ - Decimal, ! – Single, # - Double, $ - String Dim n as Integer or Dim n%

Implicit Casting:

Conversions between types can normally be achieved automatically only if by doing so we can guarantee that the value is not changed in any way.

To convert one data type say byte to another data type say integer, no data is lost during conversion that’s why compiler directly casts byte to integer .This is called implicit casting.

Explicit Casting:

There are some conversions that cannot be implicitly made between data types and the compiler will give an error if we are attempted. However we can explicitly carryout such transactions using conversion functions. When we cast one type to another we deliberately force the compiler to make the transformation.

(10)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Conversion Functions:

CByte CDec CStr CShort CDbl CDate CInt CSng CLng CBool CChar CType/DirectCast/TryCast

In VB.NET Explicit Casting is needed only if “Option Strict On” is mentioned on top of the file and only then the VB.NET language compiler treats the code as Strongly Typed Programming Language.

Increasing order of Range: Byte Æ Short Æ Integer Æ Long Æ Decimal Æ Single Æ Double Casting is done based on range and not based on size of the datatype.

Byte can be implicitly assigned to any datatype.

Short can be implicitly assigned to all datatypes except Byte and So on… Dim b as Byte : Dim n as Integer

n = b ‘Because has no chance of overflow allows Implicit Casting is done 'b = n 'Invalid because not all values of n can be assigned b

b = CByte(n) 'Explicit Casting

b = Convert.ToByte(n) 'Explicit Casting - If the value of n is not in range of 0 to 255 (range of byte) then OverFlowException is thrown.

In VB.net by default integral Overflows are checked at runtime, this ensures the type safety of the code, but at the same time it adds to performance overhead at the runtime

To Disable Overflow checks at runtime:

Project Æ Properties Æ Compile Æ Advanced Compile Options Æ Remove Overflow Checks – Check It

Boxing & Unboxing

Boxing is the term used to describe the transformation from value type to reference type (Object). The runtime creates a temporary reference-type box for the object on the heap.

Dim n as integer = 20

Dim o as object = n ‘Boxing – The value of n is boxed on Heap memory and ref to that is stored in “o”

UnBoxing is the term used to describe the transformation from reference type (Object) to value type. We use the term cast here, as this has to be done explicitly.

Dim m as integer = 20

Dim o as object = m ‘Boxing – Storing Value type as Object

Dim n as integer = CInt (o) ‘Unboxing – Extracting the value of ValueType from Object.

• When a value is boxed to an object type the object type cannot be used in mathematical operations. • When the value of object type variable cannot be assigned to variable on LHS, an Exception of type

InvalidCastException is thrown. Example:

IIf (condition as Boolean, exp1 as Object, exp2 as Object) as Object Dim m, n, max as Integer

max = CInt (IIf (m>n, m, n)) ‘m and n are boxed to Object but return value has to be unboxed. Some more Special Cases of Casting.

‘chr = n ‘Invalid 'n = chr 'Invalid chr = CChar(n) 'Invalid 'n = CInt(c) 'Invalid

We cannot cast integer to char or vice versa directly. For that we have to use special functions like AscW and ChrW

chr = ChrW(n) n = AscW(chr)

Casting of String to any datatype str = "65"

'n = str 'Invalid 'str = n 'Invalid n = CInt(str)

n = Integer.Parse(str) ‘Throws FormatException if Parsing fails n = Convert.ToInt32(str)

'Casting between integer and bool Dim n As Integer

Dim bln As Boolean 'n = bln 'Invalid 'bln = n 'Invalid

n = CInt(bln) 'Explicit casting bln = CBool(n) 'Explicit casting

(11)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Console.WriteLine("Success")

Else

Console.WriteLine("Failed") End If

In TryParse if Parsing fails, the value of second parameter (“n”) is set to default value.

str = n & "" str = CStr(n)

str = Convert.ToString(n)

Constant Declaration Const PI As Double = 3.14

'PI = 10 'Invalid – The value of constant cannot be changed.

Note: It is recomemded to have the name of constant variable always in upper case.

Enumerated Datatype

• Enums can be subtype of integral types only.

• Enum is a collection of constants.

Enum WeekDays as Integer Sun = 1 Mon Tues Wed Thus Fri Sat End Enum Dim wd As WeekDays wd = WeekDays.Tues n = 1

'wd = 1 ‘Invalid – Casting is needed. wd = CType(n, WeekDays) 'explicit casting n = wd 'implicit casting

Console.WriteLine(wd) ‘Prints the Numeric Value Console.WriteLine(wd.ToString()) ‘Print the String Value

About String and StringBuilder

Strings in .net are called as Immutable (not modifiable) objects. They are Reference Types and hence are allocated memory on heap.

Immutable means once the value of string is set it cannot be changed. Dim s as String

S = “Deccan” ‘Creates a new string on the heap.

S = S & “soft” ‘Creates another string on the heap by value “Deccansoft” and the old string “Deccan” is ready for garbage collection.

Because of the above behavour it is not recommended that the string datatype is used for those variables which need frequent modifications in their value.

Instead we should use the class called as “System.Text.StringBuilder” for those operations which need very frequent modification to the string. It allocates memory to the string in blocks and the capacity is automatically managed. Dim sb As New System.Text.StringBuilder(100)

Console.WriteLine(sb.Capacity) For i As Integer = 0 To 50 sb.Append(i) Next Console.WriteLine(sb.Capacity) str = sb.ToString()

Modified value of string must be assinged to it again otherwise the value of it doesn’t change

str = "Demo String"

str.Replace(" ", "-") ‘Incorrect Usage – str doesn’t change. Console.WriteLine(str)

str = str.Replace(" ", "-") ‘Correct Usage Console.WriteLine(str)

Operators

Arithmetic Operators: +, - , *, / (Floating Type Division), \ (Integral Division), Mod (Modulus / Remainder), ^ (Power), +=, -=, *=, ^=, /=, \=

• ^= & /= Operators can be only used with float variables.

• Dividing a Integral Type with zero throws DivideByZeroException

Floating Point Division by zero is not a runtime exception but the value would be either PositiveInfinity (if numerator is greater than zero) or NegativeInfinity (if nuderator is less than zero) or NaN(if numerator is also zero)

Dim n as Integer

Dim m as Double = -4.0 / n

If (Double.IsNaN(m)) Then Console.WriteLine(“Not a Number”)

(12)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

ElseIf (Double.IsNegativeInfinity(m)) Then Console.WriteLine("Negative Infinity")

Logical Operators:

A B A AndAlso B A OrElse B A XOR B Not A

True True True True False False

True False False True True False

False True False True True True

False False False False False True

• Is and IsNot are used to compare two reference types

Ex: (a1 Is a2) is true if both a1 and a2 are referencing to the same object. (a1 IsNot a2) is true if both a1 and a2 are not referencing to the same object.

• TypeOf: Is used to check if a given reference variable is referencing to an object of a give class. Ex: a TypeOf CA is True if a is referencing to an object of class CA or any of its subclass Relational Operators: <, >, <=, >=, <>, = (for both equal and assignment operator)

Bitwise Operators: And and OR are the only two bitwise operators supported in VB.NET • If (E1 and E2) – If E1is false then also E2 is evaluated even though result will be false only. • If (E1 AndAlso E2) - – If E1 is false then E2 is not evaluated and the result will be false only. • If (E1 Or E2) – If E1 is True then also E2 is evaluated even though result will be True only. • If (E1 OrElse E2) - – If E1 is True then E2 is not evaluated and the result will be True only. • a = b = c will not be allowed for any datatype other than Boolean.

• Note: Operators not supported in VB.NET: ++, --, ?:, <<. >>

Statements

If (C1) Then S1 --- If (C1) Then S1() ElseIf (C2) Then S2() ElseIf (C3) Then S3() Else S4() End If

• ( ) are optional with condition

Select Case n Case 1 S1() ‘if n=1 Case 2, 3 S2 ‘If n=2 or 3 Case Is < 6

S3() ‘if n= 4,5 and 0 & –ve numbers If (n = 5) Then Exit Select

S4() ‘if n= 4 and 0 & –ve numbers Case 6 To 9 S5() ‘if n=6,7,8,9 Case Else S6() ‘if n > 9 End Select GoTo Statement Dim n1 as Integer = 0 la: Console.WriteLine("s1") n1 += 1

If (n1 = 5) Then GoTo cont GoTo la

cont:

Goto is generally avoided in programming because then the clarity in code is lost.

While Loop While (n < 10) n += 1

If (n = 5) Then Continue While If (n = 7) Then Exit While Console.WriteLine(n) End While Do While (c1) ‘Excutes if c1 is True If (c2) Then Exit Do If (c2) Then Continue Do Loop Do Until (c1) ‘Excutes if c1 is False Loop Do

‘First Executes the statents and then checks for the condition

Loop Until (C1) Do

Loop While(C1)

For Loops

For i As Integer = 1 To 10 Step 1 If (i = 5) Then

Continue For End If

If (i = 7) Then

Prints all command line arguments For i = 0 To args.Length - 1 Console.WriteLine(args(i)) Next

Same result can be also achieved as

What is the output of the below prog For i As Integer = 1 To 3 Step 1 For j As Integer = 1 To 3 Step 1 If (i = j) Then

Exit For End If

(13)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

End If

Console.WriteLine(i) Next i

What is the o/p ?

Console.WriteLine(s) Next

Next Next

What is the o/p?

Note: "For Each” statement can be used only for arrays and collections i.e objects which have implemented the interface IEnumerable With Statement Console.WriteLine(args.Length) Console.WriteLine(args.Rank) With (args) Console.WriteLine(.Length) Console.WriteLine(.Rank) End With

Its not supported in C#

Working with Arrays

• Arrays are reference types and thus are allocated memory on heap.

• All arrays irrespective of their type are by default inherited from System.Array class • They always dynamic because we can set the size of the arrays at runtime.

• Size of array can never be changed at runtime.

Dim ar(X) as Integer ‘X is the variable

Dim ar(10) As Integer ‘Declared and Initialized and array of lengh 11 Dim ar(0 To 10) As Integer

Dim ar as Integer(10) ‘Invalid

Dim ar As Integer() ‘Only declaration and “ar” is by default is set to “Nothing” Dim ar() as Integer

ReDim ar(10) ‘Initializes an array of lengh 11 ReDim ar(0 To 10)

Console.WriteLine(ar.Length)

ReDim Preserve ar(0 To 20) ‘Creates a new array of 21 elements and because of the keyword Preserve copies the data from the old array into new array and the old array would be ready for garbage collection.

Dim ar() as Integer = {1, 2, 3} ‘Declares and Initializes and array of 3 elements i.e Length 3. ar = New Integer() {1, 2, 3}

Dim ar(-1) as Integer – Declares and Intialzes an Array with “0” length. Multidimensional Arrays:

Dim ar(2, 3) As Integer

Console.WriteLine(ar.Length) ‘12

Console.WriteLine(ar.Rank) ‘2 – Gives the total number of dimensions

Console.WriteLine(ar.GetLength(0)) ‘ 3 – Gives the number of elements in 1st dimension. Console.WriteLine(ar.GetLength(1)) ‘ 4 – Gives the number of elements in 2nd dimension. Dim ar( , ) As Integer

ReDim ar(2, 3)

ReDim ar(3, 4) 'No Exception and both the dimension sizes can be changed as preserve is not used. ReDim Preserve ar(3, 5) –No Exception as only outer Dimension size is changed.

ReDim Preserve ar(4, 5) 'Throws runtime ArrayTypeMisMatchException because only the Outermost dimension size can be changed if keyword preserve is used and here the inner dimension size is changed.

Dim ar(,) As Integer = {{1, 2}, {3, 4}, {5, 6}} Console.WriteLine(ar.Length) 'Prints - 6 Console.WriteLine(ar.Rank) ' Prints - 2

Console.WriteLine(ar.GetLength(0)) ' Prints - 3 ‘Gives the number of rows in a matrix. Console.WriteLine(ar.GetLength(1)) ' Prints - 2 ‘Gives the number of columns in a matrix Console.WriteLine(ar(1,1)) ‘Prints – 4

Workiing with Methods

Types of Procedues :

1. Sub Procedures – Do not return any value 2. Function Procedures – Returns a value.

(14)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

3. Property Procedures – To be covered in OOPS

In VB.NET the name of the function is treated as Variable in that function. The return type of the function is the datatype of that variable and the last value assigned to that becomes the return value of that function.

Public Class Program

Shared Sub Main(ByVal args() As String) Dim n1, n2 As Integer

n1 = Integer.Parse(args(0)) ‘Converts the command line argment to Integer. n2 = CInt(args(1))

Dim res As Integer

res = Add(n1, n2) ‘Uses the default value for third parameter Console.WriteLine(res)

Console.Write("Enter first number : ") n1 = Integer.Parse(Console.ReadLine()) Console.Write("Enter second number : ") n2 = Integer.Parse(Console.ReadLine()) res = Add(n1, n2)

Console.WriteLine("Result: " & res)

Console.WriteLine(Add("Deccan", "soft")) ‘Invokes the string parameter method res = Add(1, 2, 3, 4)

res = Add(1, 2, 3) res = Add(1, 2) res = Add(1, 2, , 4)

res = Add(1, 2, d:=4, c:=3) ‘Named Arguments – Sequence of paramets is not important. res = Add(b:=1, a:=2, d:=4, c:=3)

Dim mar() As Integer = {1, 2, 3}

res = Add(mar) ‘Invokes the Version with array parameter Console.WriteLine(res)

Console.WriteLine(Add(1, 2, 3)) ‘Invokes the version with 3 parameters Console.WriteLine(Add(1, 2, 3, 4, 5, 6)) ‘Invokes the ParamArray Version Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7))

Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7, 8)) Console.WriteLine(Add(1, 2, 3, 4, 5, 6, 7, 8, 9)) Console.WriteLine(Add(1))

End Sub

'Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer ' Return a + b

'End Function

Shared Function Add(ByVal a As Integer, ByVal b As Integer,

Optional ByVal c As Integer = 0, Optional ByVal d As Integer = 0) As Integer Return a + b + c + d

End Function

Shared Function Add(ByVal s1 As String, ByVal s2 As String) As String Return s1 & s2

End Function

Shared Function Add(ByVal ParamArray ar() As Integer) As Integer For Each n As Integer In ar

Add += n Next End Function End Class

Method Overloading:

• Having two or more methods with same name and different parameters • Parameters must be different either in their datatype or in their count.

• Method cannot be overloaded based on Return Type or ByVal/ByRef or Parameter names.

• Call to the Overloaded method is resolved at compile time and is done based on datatype and count of arguments passed to the method.

Optional Parameters

(15)

Deccansoft Software Services – VB.NET

VB.NET Language Basics

Named Arguments:

• While calling a method we can pass arguments based on parameter names and we don’t have to then pass them in sequence.

ParamArray Parameter:

• Only Parameters which are of type array can be marked as ParamArray

• If parameter is marked as ParamArray either a reference to the array can be passed as argument or otherwise 0 or more individual argurements can be passed.

• Only one parameter of a method can be declared as ParamArray Parameter. • It must be always the last parameter in the list of parameters for a given method.

• If we have other parameters in the list they must be before the ParamArray parameter and they cannot be declared as optional.

Static Local Variable Public Class Program1 Public Shared Sub Main() Foo()

Foo() Foo() End Sub

Shared Sub Foo()

Static Dim n As Integer n += 1

Console.WriteLine(n) End Sub

End Class

A local variable can be declared as static and in such case it is allocated memory when the method is called for the first time and it retains its value for the subsequent call to the same method. It doesn’t get removed from the memory unlike other local variables or parameters of a method.

Note: Static Local Variables are not supported in C# Output of the program

1 2 3

Value Type passed ByVal and ByRef Public Class Program

Public Shared Sub Main() Dim n1, n2 As Integer n1 = 10

n2 = 10 Demo(n1, n2)

Console.WriteLine(n1 & " " & n2) End Sub

Shared Sub Demo(ByVal a As Integer, ByRef b As Integer) a += 1

b += 1 End Sub End Class

The argument “n1” is passed by value (ByVal) i.e a dublicate copy of that variable is created on the stack of the function by name “a”. Any change made to parameter “a” is not reflected in “n1”

The argument “n2” is passed by reference to “b”, i.e both “b” and “n2” reference to same memory and hence change made to “b” is also reflected in “n2”.

Result: 10 11

In Main Before Foo is Called n1 = 10 n2 = 10 In Foo a = 10 11 n1 = 10 b/n2 = 10 11

In Main After Foo is returned n1 = 10

n2 = 11

Reference Type can also be passed ByVal and ByRef (this topic will be covered in OOPS) General Points:

• “:” is the Statement terminator ex: a=1 : b=2 • “_” is the Statement Continuation char

Ex: a = b _ + _ c

• If Keywords have to be used as Identifiers enclose them in [ ] ex: Function [Sub](a as Integer, b as Integer) as Integer

return a-b

End Function

• If Strings have the value as "(Quote) replace that with Double Quote ("") ex: Console.WriteLine("This is a ""Quoted"" word")

(16)

Deccansoft Software Services- MS.NET

VB.NET Examples

Program to check the range of a datatype

Public Class Max_Min_Values Public Shared Sub Main()

Console.WriteLine(Integer.MaxValue) Console.WriteLine(Integer.MinValue) Console.WriteLine(Short.MaxValue) Console.WriteLine(Short.MinValue) End Sub End Class

Program for type-casting Public Class Type_Casting Public Shared Sub Main() Dim n As Integer = 50 Dim s As Short = 5 Dim str As String = "100" Dim m As Integer

‘TO CONVERT FROM STRING TO INTEGER 'm = CInt(str)

'm = Integer.Parse(str) 'm = Convert.ToInt32(str) ' Dim bl As Boolean

' To check if string is convertible to integer and try parsing ' bl = Integer.TryParse(str, m)

m += 1

' TO CONVERT FROM INTEGER TO STRING 'str = CStr(n) 'str = n.ToString str = n & "" str = str + " Days" Console.WriteLine(str) End Sub End Class

Program to demonstrate In-Built Ascii Function: Public Class Ascii_Functions

Public Shared Sub Main() Console.WriteLine(ChrW(65)) Console.WriteLine(AscW("B")) End Sub

End Class

Program to demonstrate Boxing and UnBoxing Public Class Boxing

Public Shared Sub Main() Dim n As Integer = 65 Dim o As Object o = n 'This is Boxing Console.WriteLine(o)

n = CInt(o) ' This is UnBoxing Console.WriteLine(n)

End Sub End Class

Program to demonstrate IIF function an alternative to Ternary operator

Public Class IIF_Example Public Shared Sub Main() Dim n, m, o As Integer m = 5 n = 10 o = CInt(IIf(m < 10, m, n)) Console.WriteLine(o) End Sub End Class

Program to demonstrate If Statement Dim grade As String

Console.WriteLine("Enter a grade") grade = Console.ReadLine()

If (grade = "E" OrElse grade = "e") Then Console.WriteLine("Excellent")

ElseIf (grade = "G" OrElse grade = "g") Then Console.WriteLine("Good")

Else

Console.WriteLine("No Such Grades") End If

Program to demonstrate Select Statement Dim grade As String

Console.WriteLine("Enter a grade") grade = Console.ReadLine() Select Case (grade)

Case "E" or “e”

Console.WriteLine("Excellent") Case "G" or “g”

Console.WriteLine("Good") Case Else

Console.WriteLine("No Such Grades") End Select

Program to demonstrate GoTo statement Public Class Label_Example

Public Shared Sub Main() Console.WriteLine("One") GoTo Five Console.WriteLine("Two") Console.WriteLine("Three") Console.WriteLine("Four") Five: Console.WriteLine("Five") Console.WriteLine("Six") Console.WriteLine("Seven") Console.WriteLine("Eight") Console.WriteLine("Nine") Ten: Console.WriteLine("Ten") End Sub End Class

Program to demonstrate Select statement Public Class Select_Example

Public Shared Sub Main() Dim n As Integer = 1 Select Case n

(17)

Deccansoft Software Services- MS.NET

VB.NET Examples

Console.WriteLine(1)

Case 2, 3

Console.WriteLine(2 & " & " & 3) Case Is < 6

Console.WriteLine("Less Than 6") Case 6 To 9

Console.WriteLine("6 To 9") If (n = 7) Then Exit Select Console.WriteLine("Not 7") Case Else Console.WriteLine("Else Case") End Select End Sub End Class

Program to demonstrate While loop Public Class While_Example

Public Shared Sub Main() Dim n As Integer = 5 While (n > 0) Console.WriteLine(n) n = n - 1 End While Console.WriteLine() Do While (n < 5) Console.WriteLine(n) n = n + 1 Loop Console.WriteLine() Do Console.WriteLine(n) n = n - 1 Loop While (n > 0) End Sub End Class

Public Class WhileDemo Shared Sub Main()

Dim marks, count, avg, total As Integer Console.WriteLine("Enter 6 Subject marks") While (count < 6) marks = Console.ReadLine() total += marks count += 1 End While avg = total / 6

Console.WriteLine("Total is " & total) Console.WriteLine("Average is " & avg) End Sub

End Class

Program to demonstrate Do Until..Loop Public Class Until_Example

Public Shared Sub Main() Dim n As Integer Do Until (n = 5) Console.WriteLine(n) n = n + 1 Loop Console.WriteLine() Do Console.WriteLine(n) n = n - 1 Loop Until (n = 0) End Sub End Class

Program to generate tables from 1 to 5 using For loop Class table

Public Shared Sub Main() Dim n, m As Integer For n = 1 To 10 For m = 1 To 5

Console.Write(m & "*" & n & "=" & n * m & vbTab) Next Console.WriteLine() Next End Sub End Class

Program to generate a triangle using For loop Class triangle

Public Shared Sub Main() Dim n, m, o As Integer For n = 10 To 1 Step -1 For o = 0 To n - 1 Console.Write(" ") Next For m = n To 10 Console.Write("* ") Next Console.WriteLine() Next End Sub End Class

Program to demonstrate Arrays Public Class Array_Example Public Shared Sub Main()

Dim ar() As Integer = {1, 2, 3, 4, 5} Console.WriteLine(ar.Length) For Each tmp As Integer In ar Console.WriteLine(tmp) Next

ReDim ar(10)

For Each tmp As Integer In ar Console.WriteLine(tmp) Next

'ReDim Preserve ar(10) ‘For Each tmp As Integer In ar ‘Console.WriteLine(tmp) ‘Next

End Sub End Class

Program to demonstrate Function Overloading Public Class Functions_Example

(18)

Deccansoft Software Services- MS.NET

VB.NET Examples

Public Shared Sub Main()

Dim m, n As Integer Dim o As Short = 12 m = 10 : n=5 'Console.WriteLine(Add("Hello", "Harish")) 'Console.WriteLine(m, n) 'Console.WriteLine(Add(o, 5)) Console.WriteLine(Add(b:=10, a:=50)) End Sub

Shared Function Add(ByVal a As Short, ByVal b As Integer) As Integer

Console.WriteLine("One") Add = a + b

End Function

Shared Function Add(ByVal a As Integer, ByVal b As Integer) As Integer

Console.WriteLine("Two") Add = a + b

End Function

Shared Function Add(ByVal a As String, ByVal b As String) As String

Add = a & b End Function End Class

Program to demonstrate static variable Public Class Static_Local_Variable Public Shared Sub Main() Foo ()

Foo () Foo () Foo() End Sub

Shared Sub Foo()

Static Dim a As Integer a += 1

Console.WriteLine(a) End Sub

End Class

Program to demonstrate Value and Call-By-Reference

Public Class ByRef_ByVal Public Shared Sub Main() 'Dim m, n As Integer 'm = 5 'n = 10 'Console.WriteLine("a: " & m) 'Console.WriteLine("b: " & n) 'Foo(m, n) 'Console.WriteLine("After Foo():") 'Console.WriteLine("a: " & m) 'Console.WriteLine("b: " & n) Dim ar1() As Integer = {10, 10} Dim ar2() As Integer = {10, 10}

Console.WriteLine(ar1(0) & " " & ar2(0)) Console.WriteLine(ar1(1) & " " & ar2(1)) Foo(ar1, ar2)

Console.WriteLine(ar1(0) & " " & ar2(0)) Console.WriteLine(ar1(1) & " " & ar2(1)) End Sub

Shared Sub Foo(ByVal a As Integer, ByRef b As Integer) a += 1

b += 1 End Sub

Shared Sub Foo(ByVal a() As Integer, ByRef b() As Integer) ReDim a(1)

ReDim b(1) End Sub End Class

Program to demonstrate passing an array of fixed length to a function:

Public Class Array_Sum Public Shared Sub Main()

Dim a() As Integer = {1, 2, 3, 4, 5} Console.WriteLine(Add(a)) End Sub

Shared Function Add(ByVal a() As Integer) As Integer For Each a1 As Integer In a

Add += a1 Next End Function End Class

Program to demonstrate passing an arrays of variable length to a function

Public Class ParamArray_Example Public Shared Sub Main() Dim m, n, o As Integer m = 5 n = 10 o = 15 Console.WriteLine(Add(m, n, o, 2, 3, 4, 5, 6, 7, 8, 9, 1)) Console.WriteLine(Add(1,2,3)) Console.WriteLine(Add(m,1,n,2,0,3,4) End Sub

Shared Function Add(ByVal ParamArray a() As Integer) As Integer

For Each tmp As Integer In a Add += tmp

Next End Function End Class

(19)

Deccansoft Software Services

C# - Language Basics

Integral Types

DataType Size . Net (CTS) Comments

byte 1 System.Byte 0 - 255 It is Unsigned sbyte 1 System.SByte -128 to 127 - Signed

short 2 System.Int16 ushort 2 System.UInt16 int 4 System.Int32 uint 4 System.Unt32 long 8 System.Int64 ulong 8 System.UInt64 Floating Types

decimal 16 System.Decimal Has up to 28 digits after decimal float 4 System.Single Has up to 8 digits after decimal double 8 System.Double Has up to 15 digits after decimal Other DataTypes

char 2 System.Char Uses Unicode Charset

string * 4 Systring.String Uses Unicode Charset

bool 2 System.Boolean

object * System.Object Generic Datatype Variable Declaration Syntax:

int a,b;

int a=10, b=20;

• A local variable declared must be explicitly initialized before used in an expression otherwise gives an compilation error.

• byte, short, char types when used in an expression are automatically raised to the rank of Integer.

using System; class Program {

public static void Main() {

int n; byte b=0;

n = b; //Implicit casting

//b = n; //Invalid – Explicit casting is required n = 255;

b = (byte) n;

Console.WriteLine(b);

checked //-always checks for Overflow {

b = (byte)n; //If overflows exception is thrown }

unchecked //-Neverchecks for Overflow {

b = (byte)n; //Exception in never thrown Console.WriteLine(b); } float f = 0.6F; Console.WriteLine(f); decimal dec = 0.6M; double dbl = 0.6D;

//float and decimal requires casting dec = 10; //Integer to decimal //f = dec; //Invalid //dec = f; //Invalid f = (float)dec; dec = (decimal)f; string s = "Demo"; char c = 'S'; //int to char. n = c; //c = n; //invalid

c = (char)n; //Explicit Casting

//bool – int/anydatatype explicit or implicit casting is not allowed either ways

//string to int s = "100"; n = int.Parse(s); n = Convert.ToInt32(s); //n = (int)s;//Invalid //int to string s = n.ToString(); s = n + ""; s = Convert.ToString(n); //long to float long lng = 10;

f = lng; //Long can be casted to float lng = (long) f;

object obj = n; //Boxing n = (int)obj; //Unboxing const double PI = 3.14; byte b1, b2, b3; b1 = b2 = b3 = 10;

(20)

Deccansoft Software Services

C# - Language Basics

//if byte, short or char are used in an expression they are automatically raised to the rank of int.

b1 = (byte) (b2 + b3);

Console.WriteLine(3 / 2); //Result 1 Console.WriteLine(3.0 / 2); //Result 1.5

n = 10;

int m = n++; //m=n; n=n+1 - Post Increment Console.WriteLine(n + " " + m); m = ++n; //n=n+1; m=n - Pre Increment Console.WriteLine(n + " " + m); //?: Conditional Operator int max; max = n > m ? n : m; //?: Operator //Enum Sample n = 2; //n is int WeekDays wd = WeekDays.Sat; wd = (WeekDays) n; //n = wd; //Invalid

n = (int) wd; //In VB.NET casting is not required }

}

enum WeekDays : int {

Sun=1, Mon, Tues, Wed, Thus, Fri, Sat }

Enum is a subtype of any integral type.

Note: You cannot use the checked and unchecked keywords to control floating point (non-integer) arithmetic. The checked and unchecked keywords control only integer arithmetic. Floating point arithmetic never throws OverflowException — not even when you divide by 0.0

Operators

Arithmetic +, -, * , / , % (mod) Logical Operators ^ (XOR), !, && , ||

Ternary Operator ?: String concatenation + Increment, decrement ++ , -- Bitwise << , >>, & , | , ~ Relational = = , != , < , > , <= , >= Assignment = , += , -= , *= , /= , %= , &= , | = , ^= , <<= , >>= Type information is , sizeof , typeof, as

Indirection and Address * , -> , [] , & Note for VB.NET Programmers:

• In C# the arithmetic operator ‘/ ’ is the same for both floating point and integer datatypes and the result depends on the operands. Control Statements if-statement: if (BooleanExpression) { statement; } else if (Boolean-Expression) { statement; } else { statement; } Switch Statement int n;

switch (expr) //expr can only integral type / char / string {

case 0: //value of case must be a constant. statements;

goto default; // or break can be used. case 1:

case 2: statements;

break; //break must be preset after every case with statements default:

statements;

break; //break must be present after default also. } while…..loop while (BooleanExpression) { Statements; } do { Statements; }while (BooleanExpression)

(21)

Deccansoft Software Services

C# - Language Basics

for and foreach statements

for ( initializer; condition; iterator ) {

statements; }

foreach (DataType identifier in <Array or Collection>) {

embedded-statements; }

for (int i = 0; i < 10; i++) {

if (i == 7) break; if (i == 3) continue; Console.WriteLine(i); }

foreach (string s in args) Console.WriteLine(s);

class Program {

static void Main(string[] args) {

for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == j) break; Console.WriteLine(i + " " + j); } } } }

• break and continue statements can be used in for and while loops. • C# doesn’t support with statement

Working with Arrays 1.Single-Dimensional Arrays

int [] myArray = new int [5];

string myStringArray = new string[5]; int [] myArray = new int [] {1 , 2 , 3 };

string[] weekdays = new string[] {“Sunday”, “Monday”, ”Tuesday”};

When you initialize an array upon declaration, it is possible to use the following shortcuts: int[] myArray = {1, 3, 5, 7, 9};

string[] weekDays = {"Sun", "Sat", "Mon", "Tue"};

It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable. For example:

int[] myArray;

myArray = new int[] {1, 3, 5, 7, 9}; // OK myArray = {1, 3, 5, 7, 9}; // Error 2.MultiDimensional Arrays int[,] myArray = new int[4,2];

Also, the following declaration creates an array of three dimensions, 4, 2, and 3: int[,,] myArray = new int [4,2,3];

You can initialize the array upon declaration as shown in the following example: int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};

You can also initialize the array without specifying the rank: int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};

If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. For example:

int[,] myArray;

myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK myArray = {{1,2}, {3,4}, {5,6}, {7,8}}; // Error

class Program {

static void Main(string[] args) {

int[] ar = new int[ ] {1,2,3,4}; Console.WriteLine(a.Length); Console.WriteLine(a.Rank); foreach (int n in ar)

Console.WriteLine(n);

//To increase the size of existing array and also retaining data in it. i.e equivalent of Redim Preserve in VB. int[] temp =ar;

(22)

Deccansoft Software Services

C# - Language Basics

Array.Copy(temp, ar, temp.length);

temp=null;

foreach (int n in ar) Console.WriteLine(n); }

}

3.Jagged Arrays(Array-of-Arrays)

A jagged array is an array whose elements are arrays. A jagged array is sometimes called an "array-of-arrays." The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:

int[][] myJaggedArray = new int[3][];

Before you can use myJaggedArray, its elements must be initialized. You can initialize the elements like this example: myJaggedArray[0] = new int[5];

myJaggedArray[1] = new int[4]; myJaggedArray[2] = new int[2];

It is also possible to use initializers to fill the array elements with values, in which case youDon’t need the array size, Example

myJaggedArray[0]=new int[] {1,2,3,4,5}; myJaggedArray[1]=new int[] {1,2,3,4}; myJaggedArray[2]=new int[] {1,2};

You can also initialize the array upon declaration like this

int[][] myJaggedArray = {new int[]{1,2,3,4,5},new int[]{1,2,3,4}, new int[]{1,2}}; int[][] myJaggedArray;

myJaggedArray = new int[][] {new int[]{1,2,3,4,5},new int[]{1,2,3,4},new int[]{1,2}};

Working with functions using System;

class Program2 {

public static void Main() {

int res = Add(10, 2); int[] mar = { 1, 2, 3, 4 }; res = Add(mar); res = Add(); res = Add(1, 2, 3, 4, 5); res = Add(1, 2, 3, 4, 5, 6); res = Add(1, 2, 3, 4, 5, 6, 7); int n1, n2, n3; n1 = n3 = 10;

Foo(n1, out n2, ref n3);

Console.WriteLine(n1 + " " + n2 + " " + n3); }

//Pass by value and reference example static void Foo(int a, out int b, ref int c) {

a++; b = 20; c++; }

static int Add(int a, int b) {

return Add(a, b, 0); }

static int Add(int a, int b, int c) {

return a + b + c; }

static string Add(string s1, string s2) {

return s1 + s2; }

static int Add(params int[] ar) {

int sum = 0;

//for (int i = 0; i < ar.Length; i++) // sum += ar[i];

foreach (int n in ar) sum += n; return sum; }

}

• If a function has return type anything other than “void”, it must return a value.

• Out parameter must be initialized in the method and are generally used in situtions where we want to return more than one value from the function.

• C# doesn’t support Optional parameters with default values and Named arguments.

General Points;

(23)

Deccansoft Software Services

C# - Language Basics

class ProgramForPyramid {

staticvoid Main(string[] args) {

int k=0;

for (int i = 0; i < 4; i++) { for (int j = 0; j <= i; j++) Console.Write(k++ + "\t"); Console.WriteLine(); } } } class ProgramForMaxOf3Numbers {

staticvoid Main(string[] args) {

int n1 = int.Parse(Console.ReadLine()); int n2 = int.Parse(Console.ReadLine()); int n3 = int.Parse(Console.ReadLine()); int max = n1 > n2 ? n1 : n2;

max = max > n3 ? max : n3; Console.WriteLine(max); }

}

class ProgramForMaxOf3Numbers {

staticvoid Main(string[] args) {

string str = Console.ReadLine(); string[] ar = str.Split(' '); int sum = 0;

for (int i = 0; i < ar.Length; i++) {

sum += int.Parse(ar[i]); Console.WriteLine(ar[i]); }

Console.WriteLine("Average: " + sum / ar.Length); }

(24)

MS.NET -

Object Oriented Concepts

Overview

Class: A class is a template / skeleton / blueprint for creating an object.

Object: An Object is an entity that has properties for validations, methods for functionality and events for depicting the change of state.

Every object has the data and behavior with which they are differed. Data associated at any given instance of time is the state of an object.

Component: A ready to use third party object can be called as a Component. It can be replaced without any changes in the application. A component is generally used by a programmer as an object.

An application can be called as a collection of related objects exchanging messages with each other.

Loosely coupled objects are better than tightly coupled objects i.e. the lesser the information given to other objects the better it is as the objects are loosely coupled the dependencies are less and stronger security.

Every object oriented language should have three features • Encapsulation

• Inheritance • Polymorphism

Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation.

Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance.

The advantages of inheritance are Generalization, Extensibility and Reusability.

For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form.

Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways.

For example:

A man who knows more than one language can speak any language he knows. Here the functionality is speech and person is the object.

A faculty can take a form of Java Faculty or MSNET faculty and in both the forms he teaches, but what he teaches differs. Here functionality is teach and faculty is the object.

Object Creation and Instantiation

In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object is given through which we can access the members of the class for a given object. When an object is created all the variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to them based on their data types.

Working with Classes & Objects

Syntax in VB:

Dim <Variable name> as <Class name> or Dim <Variable name> As New <Class Name> <Variable name> = New <Class Name>

Syntax in C#:

<Class name> <Var name>; or <Class name> <Var name> = new <Class name> ( ); <Var name> = new <Class name> ( );

Account Example

1. Create a new project (File -> New Project). Give the name of project as AccountApplication. 2. In Solution Explorer, Right Click and add to the project a new class and name it as Account

References

Related documents

Our model gives two important characterisations of bubbles in economics: firstly, a rapid super-exponential growth; secondly, an illusion of certainty as described by a

Mercer county records search new jersey police arrest order for law for individuals in camden county nj public records in court and available.. Looking for sure your favorite

The present work evaluates the nutritional and feed value of fermented sweet potato meal (ProEn-K TM ) to replace soybean meal in the diet of juvenileP.

Having considered the cases of pancreas transplant loss due to immunological factors in the early postoperative period (irreversible antibody-mediated rejection in Pa- tient 29) and

using fingerprint based identification because of a better understanding of 15fingerprints and furthermore, its matching perfonnance is better than any other existing

England.. Everyone has been fascinated, from an early age, by soap bubbles and soap films. This has been no less true of the scientific community. Biologists, chemists,

rights, the definition of an issuer under federal law has been explicitly limited to owners of fractional undivided interests in oil, gas, or other mineral rights who

The ABC Program uses an automated self-service-based border clearance kiosk solution (the “ABC System”) to partially automate the processing of eligible travellers