getting started with c# programming

36
Getting Started With C# Programming Bhushan Mulmule bhushan.mulmule@dotnetvideotutoria l.com www.dotnetvideotutorial.com

Upload: bhushan-mulmule

Post on 10-May-2015

590 views

Category:

Technology


5 download

DESCRIPTION

Session is about how to write first program in C#. Also discusses variables, Data Types, CTS, Value Type, Reference Type, string, object, dynamic, Type Casting, Boxing Unboxing, Console.ReadLine(), Console.WriteLine()

TRANSCRIPT

Page 1: Getting started with C# Programming

Getting Started With

C# Programmin

gBhushan Mulmule

[email protected]

www.dotnetvideotutorial.com

Page 2: Getting started with C# Programming

Watch Video on www.dotnetvideotutorial.com

Page 3: Getting started with C# Programming

Agen

da

First C# Program

Complication

Execution

Command Line Args

Variables

CTS Types

Value and Reference

Types

Type Inference

Type Casting

www.dotnetvideotutorial.com

Page 4: Getting started with C# Programming

First C# Program

www.dotnetvideotutorial.com

Page 5: Getting started with C# Programming

//This is my first C# programusing System;

namespace HelloWorld{ class FirstProgram { static void Main() { Console.WriteLine("Hello World");

Console.ReadKey(); } }}

www.dotnetvideotutorial.com

Page 6: Getting started with C# Programming

Compilation And Execution

>CSC FirstProgram.cs

>FirstProgram.exe

www.dotnetvideotutorial.com

Page 7: Getting started with C# Programming

Variables

a variable is a storage location and an associated symbolic name (an identifier)

Different types of variables can be declared to store different type of data.

Variables needs to be declared before use

Typical syntax to declare variable is:

< type > < name >

For Example:

int a;

float b;

a

b

www.dotnetvideotutorial.com

Page 8: Getting started with C# Programming

//Variable Demo//Program to add two numbersusing System;

namespace VariableDemo{ class Program { static void Main(string[] args) { int no1, no2, result; no1 = 10; no2 = 20; result = no1 + no2; Console.WriteLine("Result = " + result);

Console.ReadKey(); } }}

no1

no2

Result

10

20

30

www.dotnetvideotutorial.com

Page 9: Getting started with C# Programming

CTS Types Data types in .NET are specified by CTS. Language datatype maps to CTS

datatype.

For example, int of C# maps to System.Int32 of CTS.

CTS have two categories of types: Value Type and Reference Type

Every type derived from System.Object. (Directly of Indirectly)

Data types are classes or structs that supports certain methods.

For example, string s = i.ToString();

C# has 16 predefined types

13 value types and

3 reference types (string, dynamic, object) .

CTS Types

Value TypeReference

Type

System.Object

System.ValueType

Value Types

Reference Type

Reference Typewww.dotnetvideotutorial.com

Page 10: Getting started with C# Programming

25a

67436b

3.14c

343.54d

-e

nullf

Stack

Heap

45600

Strings are cool!

45600

g 25

int a; //32 bitslong b; //64 bits float c; //32 bits double d; //64 bits char e; //16 bits string f;int g;string h;

a = 25;b = 6743674654783474;c = 3.14F;d = 4443534534.54;e = '-';f = "Strings are cool!";g = a; //Copies actual valueh = f; //Copies reference of object

...

...

h 45600

www.dotnetvideotutorial.com

Page 11: Getting started with C# Programming

Value Type

Value types store value on stack

All value types are derived implicitly from the System.ValueType.

Assigning one value type variable to another copies the actual value.

While passing to function value types by default passes parameters by value.

13 built-in value types are available (listed on next slide)

User defined value type can be created using keywords:

struct and

enum

System.Object

System.ValueType

Value Types

www.dotnetvideotutorial.com

Page 12: Getting started with C# Programming

Name CTS Type Description

sbyte System.SByte 8 bit signed integer

short System.Int16 16 bit signed integer

int System.Int32 32 bit signed integer

long System.Int64 64 bit signed integer

byte System.Byte 8 bit unsigned integer

ushort System.UInt16 16 bit unsigned integer

Uint System.UInt32 32 bit unsigned integer

ulong System.UInt64 64 bit unsigned integer

float System.Single 32 bit single precision floating point

double System.Double 64 bit single precision floating point

decimal System.Decimal 128 bit high precision decimal notation

bool System.Boolean Represents true of false

char System.Char Represents a single 1b bit character (Unicode)

www.dotnetvideotutorial.com

Page 13: Getting started with C# Programming

Reference Type

Variables of reference types store actual data on heap and references to the actual data on stack.

The actual data stored on heap is referred as object.

Assignment operation copies reference.

While passing to function reference types by default passes parameters by reference.

Three build in reference types are available: string, dynamic and object

User defined reference type can be created using keywords:

class

Interface

delegate

www.dotnetvideotutorial.com

Page 14: Getting started with C# Programming

string

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

equality operators (== and !=) are defined to compare the values of string objects, not references.

Strings are immutable--the contents of a string object cannot be changed after the object is created. Instead new object gets created

Verbatim string literals start with @ and are also enclosed in double quotation marks. For example: @"c:\Docs\Source\a.txt“. The advantage is that escape sequences are not processed

www.dotnetvideotutorial.com

Page 15: Getting started with C# Programming

static void Main(string[] args) { string s1 = "Bhushan"; s1 = s1 + " Mulmule"; Console.WriteLine("s1 = " + s1);

string s2 = s1; s2 = “Logic & Concepts";

if(s1 == s2) Console.WriteLine("s1 and s2 are same"); else Console.WriteLine("s2 is modified");

string filePath = @"c:\documents\training\"; Console.WriteLine("FilePath = " + filePath);

Console.ReadKey(); }

s1

Stack

Heap

45600

Bhushan

45600

Bhushan Mulmule

45700

s2 45700

45700

Logic & Concepts

45800

45800

www.dotnetvideotutorial.com

Page 16: Getting started with C# Programming

dynamic

bypass compile-time type checking. Instead, these operations are resolved at run time.

behaves like type object in most circumstances. Except not resolved or type checked by the compiler

variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).

www.dotnetvideotutorial.com

Page 17: Getting started with C# Programming

static void Main(string[] args) { dynamic dyn; object obj; dyn = 1; obj = 1;

System.Console.WriteLine(dyn.GetType()); System.Console.WriteLine(obj.GetType());

//Compile time error: Operator '+' cannot be applied to operands of type

'object' and 'int' obj = obj + 3; //bypasses compile-time type checking. Instead, resolves at run time.

dyn = dyn + 3;

} www.dotnetvideotutorial.c

om

Page 18: Getting started with C# Programming

object

The object type is an alias for Object in the .NET Framework.

All types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

can assign values of any type to variables of type object.

www.dotnetvideotutorial.com

Page 19: Getting started with C# Programming

Access Name Description

public Equals(Object) Determines whether the specified object is equal to the current object.

public static Equals(Object, Object) Determines whether the specified object instances are considered equal.

protected FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.

public GetHashCode Serves as a hash function for a particular type.

public GetType Gets the Type of the current instance.

protected MemberwiseClone Creates a shallow copy of the current Object.

public static ReferenceEquals Determines whether the specified Object instances are the same instance.

public ToString Returns a string that represents the current object.

www.dotnetvideotutorial.com

Page 20: Getting started with C# Programming

Type Inference

Local variables can be given an inferred "type" of var instead of an explicit type.

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

The variable must be initialized at the time of declaration.

The initializer cannot be null.

The initializer must be an expression.

You can’t set the initializer to an object unless you create a new object in the initializer.

The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

www.dotnetvideotutorial.com

Page 21: Getting started with C# Programming

static void Main(string[] args) { var no = 25; var pi = 3.14F; var e = 2.718281828459045; var msg = "wow!!!"; var isTrue = true;

Console.WriteLine(no.GetType()); Console.WriteLine(pi.GetType()); Console.WriteLine(e.GetType()); Console.WriteLine(msg.GetType()); Console.WriteLine(isTrue.GetType());

Console.ReadKey(); }

Output

System.Int32System.SingleSystem.DoubleSystem.StringSystem.Boolean

www.dotnetvideotutorial.com

Page 22: Getting started with C# Programming

Nullable Types

Nullable types represent value-type variables that can be assigned the value of null. (Reference types already support the null value.)

Can be declared as: <datatype>? <variablename>; for example int? x;

Can be initialized as int? x = 10; or int? x = null.

Very usefull for database operations

www.dotnetvideotutorial.com

Page 23: Getting started with C# Programming

static void Main() { int? num = null; if (num.HasValue == true) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); }

// y is set to zero int y = num.GetValueOrDefault();

Console.ReadKey(); }

www.dotnetvideotutorial.com

Page 24: Getting started with C# Programming

Type Casting

Type casting is converting an entity of one data type into another.

Types of Type Cating

Implicit Typecating

Explicit Typecasting

www.dotnetvideotutorial.com

Page 25: Getting started with C# Programming

Implicit Typecasting

Automatically done by compiler (in following circumstances)

Built-in numeric types: if a narrow type is being assigned to wider type.

(For example: long = int)

Reference types: Derived class is being assigned to base class.

int a = 25;float b;b = a;

0b

a 25

Implicit Typecasting

25.0

www.dotnetvideotutorial.com

Page 26: Getting started with C# Programming

Explicit Typecasting

Need to be done if implicit typecating is not supported For example: int = (int) long;

Can be done using typecast operators or helper methods

Data can be lost while doing Explicit conversion

Explicit conversion may fail if not possible.

Available techniques: (int)s, int.Parse(s), Convert.ToInt32(s), As operator

float x = 56.3f;int y;y = (int)x;

56.3x

0y

Explicit Typecasting

56

www.dotnetvideotutorial.com

Page 27: Getting started with C# Programming

... int a = 25;

double b = 10.5; double c; c = a + b; //a is implicitly casting to double int d; d = a + (int)b; //b has to Explicitly typecast to integer

string s1 = "100"; int i; i = int.Parse(s1); //using helper method Parse of datatype itself

string s2 = "200"; i = Convert.ToInt32(s2); //using Convert class for type conversions

object obj = 10; string str; str = obj as string;

www.dotnetvideotutorial.com

Page 28: Getting started with C# Programming

Boxing And Unboxing

Boxing:

Process of converting value type into reference type

Boxing is implicit

Unboxing:

Process of converting reference type into value type

Unboxing is explicit

Note:

Attempting to unbox null causes a NullReferenceException.

Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

www.dotnetvideotutorial.com

Page 29: Getting started with C# Programming

null

static void Main(string[] args) { int a = 25; object o; o = a; //boxing Console.WriteLine("o = {0}", o.ToString());

int b; b = (int)o; //unboxing Console.WriteLine("b = {0}", b.ToString());

Console.ReadKey(); }

25a

67436o

0b

25

Stack

Heap

67436

Boxing

Unboxing25

www.dotnetvideotutorial.com

Page 30: Getting started with C# Programming

Constant is a variable whose value cannot be changed throughout its lifetime.

Must be initialized at the time of declaration.

Always implicitly static.

Advantages:

Makes program easier to read.

Makes program easier to modify.

helps to prevent mistakes.

Constant

www.dotnetvideotutorial.com

Page 31: Getting started with C# Programming

static void Main(string[] args) { const float pi = 3.14F; int r = 5; float area = pi * r * r; Console.WriteLine("Area = " + area);

pi = 3.1415F;

Console.ReadKey(); }

www.dotnetvideotutorial.com

Page 32: Getting started with C# Programming

Reading Input using Console.ReadLine()

Console.ReadLine() is static method to read keyboard inputs

It reads a line at a time

A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or Environment.NewLine. The returned string does not contain the terminating character(s).

www.dotnetvideotutorial.com

Page 33: Getting started with C# Programming

static void Main(string[] args){ int no1, no2, result; Console.Write("Enter Number 1: "); no1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter Number 2: "); no2 = Convert.ToInt32(Console.ReadLine());

result = no1 + no2;

Console.WriteLine("{0} + {1} = {2}", no1, no2, result);

Console.ReadKey();}

0

0result

no2

0no1

25

50

75

www.dotnetvideotutorial.com

Page 34: Getting started with C# Programming

Command Line Arguments

Arguments or parameters that we can pass to Main() method from command propt.

For Ex: >greet C#

Main method need to define in one of the following ways:

The parameter of the Main method is a String array represents the command-line arguments.

static void Main(string[] args)

static int Main(string[] args)

www.dotnetvideotutorial.com

Page 35: Getting started with C# Programming

//Command line arguments demousing System;

namespace HelloWorld{ class Greet { static void Main(string[] args) { if(args.Length == 1) Console.WriteLine("Hello " + args[0]); else Console.WriteLine("Invalid Arguments");

Console.ReadKey(); } }}

C#args

0

Page 36: Getting started with C# Programming

Bhushan Mulmule

[email protected]

www.dotnetvideotutorial.com