Вы находитесь на странице: 1из 87

Getting Started

With C#
Programming
First C# Program
www.dotnetvideotutorial.com
//This is my first C# program
using System;

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

Console.ReadKey();
}
}
}
www.dotnetvideotutorial.com
Compilation And Execution
>CSC FirstProgram.cs
>FirstProgram.exe
www.dotnetvideotutorial.com
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
//Variable Demo
//Program to add two numbers
using 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
System.Object
System.ValueType
Value Types
Reference Type
Reference Type
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) .
www.dotnetvideotutorial.com
25 a
67436 b
3.14 c
343.54 d
- e
null f
Stack Heap
45600 Strings are cool!
45600
g 25
int a; //32 bits
long 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 value
h = f; //Copies reference of object
...
...
h 45600
www.dotnetvideotutorial.com
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

www.dotnetvideotutorial.com
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
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
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
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
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
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.com
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
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 Finalize Allows 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
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 cant 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
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.Int32
System.Single
System.Double
System.String
System.Boolean
www.dotnetvideotutorial.com
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
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
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
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;
0
b
a
25
Implicit
Typecasting
25.0
www.dotnetvideotutorial.com
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.3 x
0 y
Explicit
Typecasting
56
www.dotnetvideotutorial.com
...
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
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
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();
}
25 a
67436
o
0
b
25
Stack Heap
67436
Boxing
Unboxing
25
www.dotnetvideotutorial.com
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
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
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
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
0 result
no2
0 no1 25
50
75
www.dotnetvideotutorial.com
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
//Command line arguments demo
using 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
What Is The .NET Framework?
Base Class Libraries
The CLR
JIT & NGEN Garbage Collector Security Model Exception Handling Loader & Binder
WPF Win Forms DLR ASP.NET WCF
and
more!
LINQ-to-
SQL
.NET 4.0 Overview: New & Updated
CLR & Framework
The CLR
The Base Class Library
Performance, Concurrency &
Parallelization
New Languages (F#, IronPython)
Language Enhancements
Dynamic Language Runtime
Code Contracts
Managed Extensibility Framework (MEF)
Platforms
Entity Framework
WPF
Windows Workflow
ASP.NET
ASP.NET MVC
Web Forms
ASP.NET AJAX
.NET 4.0 Overview: New & Updated
CLR & Framework
The CLR
The Base Class Library
Performance, Concurrency &
Parallelization
New Languages (F#, IronPython)
Language Enhancements
Dynamic Language Runtime
Code Contracts
Managed Extensibility Framework (MEF)
Platforms
Entity Framework
WPF
Windows Workflow
ASP.NET
ASP.NET MVC
Web Forms
ASP.NET AJAX
.NET Framework Improvements
The Goals of CLR 4
Working Better Together




Faster




With Fewer Bugs
In-Proc SxS
Native/Managed Interop DLR Integration
Managed Extensibility Framework
Threading Parallel Extensions
Garbage Collection Profiling
Code Contracts Debugging Corrupted State Exceptions
Base Class Library Additions
Numerics
BigInteger

Data Structures
Tuple (new Tuple<int,int,string>(1,2,Test))
ISet<T> (SortedSet<T> & HashSet<T>)

I/O
Memory-Mapped File
Performance, Concurrency, and
Parallel Extensions
Thread-safe collections
(BlockingCollection<T>, ConcurrentDictionary<T>, etc.)
Task Parallel Library (TPL)

PLINQ

Lazy Initialization
eg: Lazy<IEnumerable<Order>> Orders { get; set;}
Code Contracts
Design By Contract
Code Contracts provide a
language-agnostic and declarative way to express
coding assumptions in .NET programs.
A Code Contract contains
Pre-conditions: must be true before
public Rational(int numerator, int denominator)
{
Contract.Requires(denominator > 0);

}

Post-conditions: must be true after

public string GetPassword()
{
Contract.Ensures(Contract.Result<string>() != null);

return password;
}

A Code Contract contains
Pre-conditions: must be true before
public Rational(int numerator, int denominator)
{
Contract.Requires(denominator > 0);

}

Post-conditions: must be true after

public string GetPassword()
{
Contract.Ensures(Contract.Result<string>() != null);

return password;
}

Code Contracts
Why are Contracts Useful?
Debugging

Tooling!
Pex (research.microsoft.com/projects/pex/)
Language Enhancements
C#, Visual Basic, plus new Functional & Dynamic Languages
New C# 4.0 Features
1.Improved COM Inter-op
2.Named and Optional Parameters
3.Covariance and Contravariance
New VB10 Features
1.Auto-Implemented Properties
2.Collection Initializers
3.Statement Lambdas
4.Implicit Line Continuation
5.Covariance and Contravariance
New VB10 Features
1.Auto-Implemented Properties
2.Collection Initializers
3.Statement Lambdas
4.Implicit Line Continuation
5.Covariance and Contravariance
Covariance & Contravariance
Fix generics
Covariance
Describes the substitution of related types, such that the
ordering from the more restrictive type to the less restrictive
type is preserved


Covariance
Describes the substitution of related types, such that the
ordering from the more restrictive type to the less restrictive
type is preserved


Contravariance
Describes the substitution of related types, such that the
ordering from the more restrictive type to the less restrictive
type is reversed.
Contravariance
Describes the substitution of related types, such that the
ordering from the more restrictive type to the less restrictive
type is reversed.
Declarative
Concurrent Dynamic
Emerging Language Trends
Declarative
Concurrent Dynamic
Emerging Language Trends
Introducing F#!
F# Is
A functional programming language derived from OCaml and
the ML family of languages
Very good for computation-intensive problems, highly-parallel
problems, and language-oriented programming
A first-class .NET 4.0 language, with full Visual Studio 2010
support
Declarative
Concurrent Dynamic
Emerging Language Trends
New C# 4.0 Features
1.Improved COM Inter-op
2.Named and Optional Parameters
3.Covariance and Contravariance
Dynamic Language Runtime
Why a Dynamic Language Runtime?
Common Language Runtime
Statically-Typed
C#
VB
Ruby
Python
Dynamically-Typed
Dynamic Language Runtime
Python
Binder
Ruby
Binder
COM
Binder
JScript
Binder
Object
Binder
.NET Dynamic Programming
Dynamic Language Runtime
Expression Trees Dynamic Dispatch Call Site Caching
IronPython IronRuby C# VB.NET whatever!
Dynamic Language Runtime
Declarative
Concurrent Dynamic
Emerging Language Trends
Declarative Development
ASP.NET Web Forms (ASPX)

XAML (WPF & Silverlight)

Code Contracts

MEF!

Managed Extensibility Framework (MEF)
What is MEF?
MEF is
A way to manage dependencies
A way to provide extensibility in your apps
A framework to encourage loose coupling and reusability
A new addition to the Base Class Library
System.ComponentModel.Composition
What is MEF? (Simple Answer)
Imports and Exports
What is MEF? (Simple Answer)
Imports and Exports
What is MEF? (Complex Answer)
Imports and Exports
of components (parts)
wired together via containers
Implementing MEF
and, heck everything else!
Whats New in the Platforms?
WPF, ASP.NET, Workflow, etc!
Windows Presentation Framework
(WPF)
Lots of Good Stuff for WPF
Multitouch
Windows 7 taskbar
Windows 7 ribbon
Full Trust XBaps
Cached compositions
Textclarity
Layout rounding
ClickOnce improvements
Focus mgt improvements
Support for UIAccessible2
VSM integration
Media element improvements
Client profile
Data controls
Accessibility improvements
Control themes
Chart controls
hundreds of good bug fixes too!
Entity Framework
Its not just for databases anymore!
EF4 Enhancements
Model-First Development
Persistence Ignorance (POCO support!)
Application Patterns
(Repository, Unit of Work, etc.)
Customization of Queries & Generated Code
Windows Workflow
WF challenges today
Limited support for XAML-only workflows
Versioning is problematic
Composition difficult or impossible
Writing custom activities and managing data flow is not easy
enough today
Limited WCF integration and activity support
No generic server host environment
Bottom line: A high bar to get to enough value to make it worth
the tax
Moving towards .NET 4.0
XAML-only workflows are the new default
Unified model between WF, WCF, and WPF
Extended base activity library
Simplified WF programming model
Support for arguments, variables, expressions
Major improvements to WCF integration
Runtime and designer improvements
Hosting & management via "Dublin"
Flow control
Flowchart
ForEach
DoWhile
Break
WCF
Send
Receive
SendReply
SendParameters
ReceiveParameters
CorrelationScope
InitializeCorrelation

Others
Assign
MethodInvoke
Persist
Interop
PowerShellCommand
...
Extended base activity library
.NET 4.0 comes with several new activities
Microsoft is planning to ship more activities via CodePlex
New flow chart model
Flowcharts offer a middle ground between the sequential and
state machine models
Simple step-by-step model,
with decisions and switches
Allows you to return to previous
activities in the workflow
Improving the Web
ASP.NET MVC, Web Forms, and ASP.NET AJAX
ASP.NET MVC
v.2 Officially part of the framework
New Features for v2:
Areas
Data Annotations support
Templated Helpers
Client-Side Validation
Web Forms
Client ID manipulation
Fine-Grained ViewState control
ASP.NET AJAX
Client-Side Templates
Client-Side Data Controls (DataView & DataContext)
Declarative Instantiation
Command Bubbling
Live Bindings

Вам также может понравиться