SlideShare une entreprise Scribd logo
1  sur  88
 C# (pronounced CSharp) is no doubt
the language of choice in .NET
Environment.
 It is an Object Oriented Programming
Language has its core and many
features similar to C++ and Java.
 But it is easy to learn and to develop as
compare to C++ and Java.
 Its design is more in tune with modern
developer tools than both of those other
languages, and it has been designed to
provide.
 simultaneously, the ease of use of
Visual Basic and the high-performance,
low-level memory access of C++,if
required.
 Automatic cleanup of dynamically
allocated memory.
 The facility to mark classes or methods
with user-defined attributes. This can
be useful for documentation and can
have some effects on compilation
 Full access to the .NET base class
library, as well as easy access to the
Windows API
 Pointers and direct memory access are
available if required, but the language
has been designed in such a way that
you can work without them in almost
all cases.
 Support for properties and events in
the style of Visual Basic.
 C# can be used to write ASP.NET
dynamic web pages and XML Web
services.
Program
File 2.cs File n.cs
Namespace B
{….}
Namespace
C{…}
Class 2 {….} Class n {…}
File 1.cs
Namespace
A{…}
Class 1{…}
 Variable : It is a placeholder where it stores
the specified data values and varies by
requirement.
 Rules:- These may start with alphabets are
with underscore(„_‟) symbol
 These may contain numeric's also.
 It won‟t allow special characters like @,#,!,$,%
etc.
 You can‟t use keywords as Variables.
 Ex: xyz,_abc,abc123, etc.
 In .NET Environment CLR categories all
DataTypes into two ways, those are
 1.Value Type: The DataTypes which are derived
from system level are called as “ValueTypes”.
 These are stored in Stack memory
 Ex: int,float,bool,double, etc.
 2.ReferenceTypes: The DataTypes which are
derived from class level are called as
“RefernceTypes”.
 These are stored in Heap Memory.
 Ex: class, object, string, etc.
 These are the key notations pre defined by
CLR in .NET Environment.
 These contains a special meaning to use in
Program.
 You can‟t use these as keywords.
 Ex: class, interface, int, static, abstract, etc.
 Comments
◦ Comments can be created using //…
◦ Multi-lines comments use /* … */
◦ Comments are ignored by the compiler
◦ Used only for human readers
 Namespaces
◦ Groups related C# features into a categories
◦ Allows the easy reuse of code
◦ Many namespaces are found in the .NET framework library
◦ Must be referenced in order to be used
 White Space
◦ Includes spaces, newline characters and tabs
 These are special symbols which will operate on values or variables.
 These symbols specifies a action to be done, that is already known
to compiler.
 It support a set of Operators those are
 Arithmetic operators
 Conditional operators
 Bitwise operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and decrement operators
 Special operators[ comma(,), sizeof().
[+,-,*,/,%]
[condition ? true, false:
]
[&, |,^,<<,>>,~]
[==,<=,>=,>,<,!=]
[&&,||,!]
[=,+=,/=,-=,*=]
[++,--]
 These are basic building block of program that controls flow
of program.
 It executes a particular block based on Boolean condition .
 C# comes with set of conditional statements, are
If statements
If else
Nested if
Switch
Ternary statements.
If(condition)
{body}
Ex: if(m%2==0)
{“even number”}
Ex: if(m%2==0)
{“even number”}
else
{“Odd number”}
switch(condition)
{
Case”1”://do
//break;
case “n”: //do
Break;
}
If(condition)
{body}
Else
{body}
 break
◦ Exit inner-most loop
 continue
◦ End iteration of inner-most loop
 goto <label>
◦ Transfer execution to label statement
 return [<expression>]
◦ Exit a method
 throw
◦ Used in exception handling
 These statements should control the flow of program, to repeat the
particular action.
 C# provides a set of control statements those are
Initialization;
While(condition)
{//body;
//inc or dec;
}
Initialization;
Do
{
//body;
//inc or dec;
} While(condition);
while:
do while: for loop
for(initialization ;condition ;inc/dec)
{
//body;
}
foreach
foreach( data type variable name in
collection name)
{
//body;
}
• foreach is new control statement
•In c# which is used to operate on
collection
•It won‟t take any starts or ends and
conditions
 Array is a collection of similar data types.
 It stores continuously in memory with zero
based index values.
 Types:
1.1D Array
2. Multi Dimensional
Array
3. Jagged Array
 1D Array: contains only single
dimension of elements .
Syntax:
Type[] name;
Declaration:
Type[] name =new type[size];
Initialization:
type[] name=new type[size]{v1,v2,..V n}
Multi dimension array contain
both rows and columns.
Syntax:
type[ , ]=new type[r size, c
size];
Initialization:
int[] arr=new int[2,3]
{ {1,2,3},
{4,5,6}
}
 Jagged Array: An Array of Arrays is called as
“jagged Array”.
 New array type introduced in C#.
 Syntax:
type[ ][ ] name=new type[ size] [ ];
Ex: int [ ][ ] myarray =new int[3] [ ];
Initialization:
int[ ][ ] myarray=new int[3] [ ];
myarray[0]=new int[ size] {v1,v2…}
myarray[1]=new int[ size] {v1,v2…}
myarray[2]=new int[ size] {v1,v2…}
•In c# array class was contain so many
in built methods and properties for
simplifying operations on arrays.
•Like Array.Sort() ,Array.Reverse() etc.
 Objects, instances and classes
 Identity
◦ Every instance has a unique identity, regardless
of
its data
 Encapsulation
◦ Data and function are packaged together
◦ Information hiding
◦ An object is an abstraction
 User should NOT know implementation details
 Properties:
◦ Breed
◦ Age
◦ Color
◦ Weight
◦ Shot Record
 Methods:
◦ sit()
◦ layDown()
◦ eat()
◦ run()
 A Class in OOP encapsulates properties and
methods
 A class, like a blueprint, is used to make
instances or objects
 Property Values:
◦ Name: Kazi
◦ Breed: Border
Collie
◦ Age: 2 years
◦ Color: Black and
White
◦ Weight: 23
Pounds
 Properties:
 Name
Breed
 Age
 Color
 Weight
Create
Instance
 Methods:
 Sit
 Play
Dead
 Eat
 Run
 Methods:
 Sit
 Play Dead
 Eat
 Run
 Use the new operator to create an object of
a class
 Properties and methods of the object can
now be accessed
Button MyButton = new Button();
Button.Text=“ Click Me”;
 Classes have the
following modifier:
◦ new*
◦ public
◦ protected*
◦ internal
◦ private*
◦ abstract
◦ sealed
◦ static **
* only usable on nested
classes
** C# 2.0
Defaults:
internal (for non-
nested classes)
private (for nested
classes)
non-abstract
non-sealed
non-static
 public
◦ Anyone can access
 protected
◦ Private to containing type and any derived types
 internal
◦ Public inside of the assembly (the .exe or .dll) no one else
may access
 protected internal
◦ Public inside of the assembly or private to types derived
from the containing class
 private (default)
◦ Access limited to the containing type
Polymorphism
The ability to use an object without knowing
its precise type
Three main kinds of polymorphism
•Inheritance
•Interfaces
•Late binding
Dependencies
For reuse and to facilitate development,
systems should be loosely coupled
Dependencies should be minimized
 In OOP, types are arranged in a
hierarchy
◦ A Base class is the parent class
◦ A Derived class is the child class
 Object is the Base class of all
other types in C#
 C# only allows single inheritance
of classes
 C# allows multiple inheritance of
interfaces
Object
Animal
Dog
 An interface defines a contract
◦ An interface is a type
◦ Includes methods, properties, indexers, events
◦ Any class or struct implementing an interface must
support all parts of the contract
 Interfaces provide no implementation
◦ When a class or struct implements an interface it
must provide the implementation
 Interfaces provide polymorphism
◦ Many classes and structs may implement
a particular interface
public interface IDelete {
void Delete();
}
public class TextBox : IDelete {
public void Delete() { ... }
}
public class Car : IDelete {
public void Delete() { ... }
}
TextBox tb = new TextBox();
IDelete iDel = tb;
iDel.Delete();
Car c = new Car();
iDel = c;
iDel.Delete();
interface IControl {
void Paint();
}
interface IListBox: IControl {
void SetItems(string[] items);
}
interface IComboBox: ITextBox, IListBox {
}
 Classes and structs can inherit from
multiple interfaces
 Interfaces can inherit from multiple interfaces
interface IControl {
void Delete();
}
interface IListBox: IControl {
void Delete();
}
interface IComboBox: ITextBox, IListBox {
void IControl.Delete();
void IListBox.Delete();
}
 If two interfaces have the same method
name, you can explicitly specify interface +
method name to disambiguate their
implementations
 Both are user-defined types
 Both can implement multiple interfaces
 Both can contain
◦ Data
 Fields, constants, events, arrays
◦ Functions
 Methods, properties, indexers, operators, constructors
◦ Type definitions
 Classes, structs, enums, interfaces, delegates
Class Struct
Reference type Value type
Can inherit from any
non-sealed reference type
No inheritance
(inherits only from System.ValueType)
Can have a destructor No destructor
Can have user-defined
parameterless constructor
No user-defined parameterless
constructor
public class Car : Vehicle {
public enum Make { GM, Honda, BMW }
Make make;
string vid;
Point location;
Car(Make m, string vid; Point loc) {
this.make = m;
this.vid = vid;
this.location = loc;
}
public void Drive() {
Console.WriteLine(“vroom”); }
}
Car c =
new Car(Car.Make.BMW,
“JF3559QT98”,
new Point(3,7));
c.Drive();
public struct Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int X { get { return x; }
set { x = value; } }
public int Y { get { return y; }
set { y = value; } }
}
Point p = new Point(2,5);
p.X += 100;
int px = p.X; // px = 102
 By default, members are per instance
◦ Each instance gets its own fields
◦ Methods apply to a specific instance
 Static members are per type
◦ Static methods can‟t access instance data
◦ No this variable in static methods
 Don‟t abuse static members
◦ They are essentially object-oriented
global data and global functions
 An abstract class is one that cannot
be instantiated
 Intended to be used as a base class
 May contain abstract and non-abstract
function members
 Similar to an interface
 Cannot be sealed
 A sealed class is one that cannot be used as a
base class
 Sealed classes can‟t be abstract
 All structs are implicitly sealed
 Why seal a class?
◦ To prevent unintended derivation
◦ Code optimization
 Virtual function calls can be resolved at compile-time
class Person {
string name;
public Person(string name) {
this.name = name;
}
public void Introduce(Person p) {
if (p != this)
Console.WriteLine(“Hi, I‟m “ + name);
}
}
 The this keyword is a predefined variable
available in non-static function members
◦ Used to access data and function members
unambiguously
class Shape {
int x, y;
public override string ToString() {
return "x=" + x + ",y=" + y;
}
}
class Circle : Shape {
int r;
public override string ToString() {
return base.ToString() + ",r=" + r;
}
}
 The base keyword is used to access class
members that are hidden by similarly named
members of the current class
 Similar to a const, but is initialized at
run-time in its declaration or in a constructor
◦ Once initialized, it cannot be modified
 Differs from a constant
◦ Initialized at run-time (vs. compile-time)
 Don‟t have to re-compile clients
◦ Can be static or per-instance
public class MyClass {
public static readonly double d1 = Math.Sin(Math.PI);
public readonly string s1;
public MyClass(string s) { s1 = s; } }
public class Button: Control {
private string caption;
public string Caption {
get { return caption; }
set { caption = value;
Repaint(); }
}
}
Button b = new Button();
b.Caption = "OK";
String s = b.Caption;
 A property is a virtual field
 Looks like a field, but is implemented with
code
 Can be
read-only,
write-only,
or read/write
public class ListBox: Control {
private string[] items;
public string this[int index] {
get { return items[index]; }
set { items[index] = value;
Repaint(); }
}
}
ListBox listBox = new ListBox();
listBox[0] = "hello";
Console.WriteLine(listBox[0]);
 An indexer lets an instance behave as a
virtual array
 Can be overloaded (e.g. index by int and by
string)
 Can be
read-only,
write-only,
or read/write
 All code executes in a method
◦ Constructors, destructors and operators are special
types of methods
◦ Properties and indexers are implemented with
get/set methods
 Methods have argument lists
 Methods contain statements
 Methods can return a value
◦ Only if return type is not void
 By default, data is passed by value
 A copy of the data is created and passed
to the method
 For value types, variables cannot be modified
by a method call
 For reference types, the instance can be
modified by a method call, but the variable
itself cannot be modified by a method call
void RefFunction(ref int p) {
p++;
} int x = 10;
RefFunction(ref x);
// x is now 11
 The ref modifier causes arguments to be
passed by reference
 Allows a method call to modify a variable
 Have to use ref modifier in method definition
and the code that calls it
 Variable has to have a value before call
void OutFunction(out int p) {
p = 22;
} int x;
OutFunction(out x);
// x is now 22
 The out modifier causes arguments to be
passed out by reference
 Allows a method call to initialize a variable
 Have to use out modifier in method
definition and the code that calls it
 Argument has to have a value before
returning
void Print(int i);
void Print(string s);
void Print(char c);
void Print(float f);
int Print(float f); // Error: duplicate signature
 A type may overload methods, i.e. provide
multiple methods with the same name
 Each must have a unique signature
 Signature is based upon arguments only, the
return value is ignored
int Sum(params int[] intArr) {
int sum = 0;
foreach (int i in intArr)
sum += i;
return sum;
}
int sum = Sum(13,87,34);
 Methods can have a variable number of
arguments, called a parameter array
 params keyword declares parameter array
 Must be last argument
class Foo {
public void DoSomething(int i) {
...
}
}
Foo f = new Foo();
f.DoSomething();
 Methods may be virtual or non-virtual
(default)
 Non-virtual methods are not polymorphic
◦ They cannot be overridden
 Non-virtual methods cannot be abstract
 Defined in a base class
 Can be overridden in derived classes
◦ Derived classes provide their own specialized
implementation
 May contain a default implementation
◦ Use abstract method if no default implementation
 A form of polymorphism
 Properties, indexers and events can also
be virtual
class Shape {
public virtual void Draw() { ... }
}
class Box : Shape {
public override void Draw() { ... }
}
class Sphere : Shape {
public override void Draw() { ... }
}
void HandleShape(Shape s) {
s.Draw();
...
} HandleShape(new Box());
HandleShape(new Sphere());
HandleShape(new Shape());
 An abstract method is virtual and has no
implementation
 Must belong to an abstract class
 Intended to be implemented in a derived
class
abstract class Shape {
public abstract void Draw();
}
class Box : Shape {
public override void Draw() { ... }
}
class Sphere : Shape {
public override void Draw() { ... }
}
void HandleShape(Shape s) {
s.Draw();
...
}
HandleShape(new Box());
HandleShape(new Sphere());
HandleShape(new Shape()); // Error!
 Instance constructors are special methods
that are called when a class or struct is
instantiated
 Performs custom initialization
 Can be overloaded
 If a class doesn‟t define any constructors, an
implicit parameterless constructor is created
 Cannot create a parameterless constructor
for
a struct
◦ All fields initialized to zero/null
class B {
private int h;
public B() { }
public B(int h) { this.h = h; }
}
class D : B {
private int i;
public D() : this(24) { }
public D(int i) { this.i = i; }
public D(int h, int i) : base(h) { this.i = i; }
}
 One constructor can call another with a
constructor initializer
 Can call this(...) or base(...)
 Default constructor initializer is base()
 A static constructor lets you create
initialization code that is called once for the
class
 Guaranteed to be executed before the first
instance of a class or struct is created and
before any static member of the class or
struct is accessed
 No other guarantees on execution order
 Only one static constructor per type
 Must be parameterless
class Foo {
~Foo() {
Console.WriteLine(“Destroyed {0}”, this);
}
}
 A destructor is a method that is called before
an instance is garbage collected
 Used to clean up any resources held by the
instance, do bookkeeping, etc.
 Only classes, not structs can have destructors
 Unlike C++, C# destructors are non-
deterministic
 They are not guaranteed to be called at a
specific time
 They are guaranteed to be called before
shutdown
 Use the using statement and the
IDisposable interface to achieve
deterministic finalization
class Car {
string vid;
public static bool operator ==(Car x, Car y) {
return x.vid == y.vid;
}
}
 User-defined operators
 Must be a static method
+ - ! ~
true false ++ --
 Overloadable unary operators
 Overloadable binary operators
+ - * / ! ~
% & | ^ == !=
<< >> < > <= >=
 No overloading for member access, method
invocation, assignment operators, nor these
operators: sizeof, new, is, as, typeof,
checked, unchecked, &&, ||, and ?:
 The && and || operators are automatically
evaluated from & and |
 Overloading a binary operator (e.g. *)
implicitly overloads the corresponding
assignment operator (e.g. *=)
 The is operator is used to dynamically test if
the run-time type of an object is compatible
with a given type
static void DoSomething(object o) {
if (o is Car)
((Car)o).Drive();
}
 Don’t abuse the is operator: it is preferable to
design an appropriate type hierarchy with
polymorphic methods
 The as operator tries to convert a variable to
a specified type; if no such conversion is
possible the result is null
static void DoSomething(object o) {
Car c = o as Car;
if (c != null) c.Drive();
}
 More efficient than using is operator: test and
convert in one operation
 Same design warning as with the is operator
 The typeof operator returns the
System.Type object for a specified type
 Can then use reflection to dynamically obtain
information about the type
Console.WriteLine(typeof(int).FullName);
Console.WriteLine(typeof(System.Int).Name);
Console.WriteLine(typeof(float).Module);
Console.WriteLine(typeof(double).IsPublic);
Console.WriteLine(typeof(Car).MemberType);
 A delegate is a reference type that defines a
method signature
 A delegate instance holds one or more
methods
◦ Essentially an “object-oriented function pointer”
◦ Methods can be static or non-static
◦ Methods can return a value
 Provides polymorphism for individual
functions
 Foundation for event handling
delegate double Del(double x); // Declare
static void DemoDelegates() {
Del delInst = new Del(Math.Sin); // Instantiate
double x = delInst(1.0); // Invoke
}
 A delegate can hold and invoke multiple
methods
◦ Multicast delegates must contain only methods
that return void, else there is a run-time
exception
 Each delegate has an invocation list
◦ Methods are invoked sequentially, in the order
added
 The += and -= operators are used to add and
remove delegates, respectively
 += and -= operators are thread-safe
delegate void SomeEvent(int x, int y);
static void Foo1(int x, int y) {
Console.WriteLine("Foo1");
}
static void Foo2(int x, int y) {
Console.WriteLine("Foo2");
}
public static void Main() {
SomeEvent func = new SomeEvent(Foo1);
func += new SomeEvent(Foo2);
func(1,2); // Foo1 and Foo2 are called
func -= new SomeEvent(Foo1);
func(2,3); // Only Foo2 is called
}
 Could always use interfaces instead of
delegates
 Interfaces are more powerful
◦ Multiple methods
◦ Inheritance
 Delegates are more elegant for event handlers
◦ Less code
◦ Can easily implement multiple event handlers on
one class/struct
 Event handling is a style of programming
where one object notifies another that
something of interest has occurred
◦ A publish-subscribe programming model
 Events allow you to tie your own code into the
functioning of an independently created
component
 Events are a type of “callback” mechanism
 Events are well suited for user-interfaces
◦ The user does something (clicks a button, moves a
mouse, changes a value, etc.) and the program
reacts in response
 Many other uses, e.g.
◦ Time-based events
◦ Asynchronous operation completed
◦ Email message has arrived
◦ A web session has begun
 C# has native support for events
 Based upon delegates
 An event is essentially a field holding a
delegate
 However, public users of the class can only
register delegates
◦ They can only call += and -=
◦ They can‟t invoke the event‟s delegate
 Multicast delegates allow multiple objects to
register with the same event
 Define the event signature as a delegate
 Define the event and firing logic
public delegate void EventHandler(object sender,
EventArgs e);
public class Button {
public event EventHandler Click;
protected void OnClick(EventArgs e) {
// This is called when button is clicked
if (Click != null) Click(this, e);
}
}
 Define and register an event handler
public class MyForm: Form {
Button okButton;
static void OkClicked(object sender, EventArgs e) {
ShowMessage("You pressed the OK button");
}
public MyForm() {
okButton = new Button(...);
okButton.Caption = "OK";
okButton.Click += new EventHandler(OkClicked);
}
}
 Anonymous methods let you declare a
method body without giving it a name.
 Behind the scenes, they exist as
'normal' methods;
 Anonymous methods can only be
created when using delegates and, in
fact, they are created using
the delegate keyword.
class Program
{
static void Main(string[] args)
{
new ShoppingCart().Process(
new Func<bool,int>(delegate(bool x){ return x ? 10 : 5; } ));
}
}
The true power of anonymous
methods can be seen when using
.NET methods that expect delegates
as parameters and when responding
to events.
Previously, you had to create a
method for every possible action you
wanted to take.
 Lambda expression is an inline
delegate introduced with C #
3.0 language.
 It‟s a concise way to represent
an anonymous method.
 Lambda expression uses the
type inference feature of C#
3.0
Both
anonymous methods and
Lambda expressions allow
you define the method
implementation inline,
however, an anonymous
method explicitly requires
you to define the parameter
types and the return type for
a method.
Parameter=> execution code
public static void SimpleLambdExpression()
{ List<int> numbers = new
List<int>{1,2,3,4,5,6,7};
var evens = numbers.FindAll(n => n % 2 == 0);
var evens2 = numbers.FindAll((int n) => { return
n % 2 == 0; });
ObjectDumper.Write(evens);
ObjectDumper.Write(evens2);
}
 Strongly typed
◦ No implicit conversions to/from int
◦ Operators: +, -, ++, --, &, |, ^, ~
 Can specify underlying type
◦ Byte, short, int, long
enum Color: byte
{
Red = 1,
Green = 2,
Blue = 4,
Black = 0,
White = Red | Green | Blue,
}
 Begin with a simple array of, say, Customers.
Customer[] customers = new Customer[30];
customers[0] = new Customer(…);
…
customers[29] = new Customer(…);
A C# language extension:
Use SQL-like syntax in C#.
LINQ
 Find the names of all London customers:
List<string> londoners = new List<string>();
foreach (Customer c in customers) {
if (c.City == “London”) {
londoners.add(c.Name);
}
}
string[] londoners =
from c in customers
where c.City ==
“London”
select c.Name;
Declarative!
SQL-like!
No loops!
 It‟s often necessary to associate information
(metadata) with types and members, e.g.
◦ Documentation URL for a class
◦ Transaction context for a method
◦ XML persistence mapping
◦ COM ProgID for a class
 Attributes allow you to decorate a code
element (assembly, module, type, member,
return value and parameter) with additional
information
 Attributes are superior to the alternatives
◦ Modifying the source language
◦ Using external files, e.g., .IDL, .DEF
 Attributes are extensible
◦ Attributes allow to you add information not
supported by C# itself
◦ Not limited to predefined information
 Built into the .NET Framework, so they work
across all .NET languages
◦ Stored in assembly metadata
Attribute Name Description
Browsable
Should a property or event be displayed in
the property window
Serializable Allows a class or struct to be serialized
Obsolete Compiler will complain if target is used
ProgId COM Prog ID
Transaction Transactional characteristics of a class
 Some predefined .NET Framework attributes
 Attributes can be
◦ Attached to types and members
◦ Examined at run-time using reflection
 Completely extensible
◦ Simply a class that inherits from System.Attribute
 Type-safe
◦ Arguments checked at compile-time
 Extensive use in .NET Framework
◦ XML, Web Services, security, serialization,
component model, COM and P/Invoke interop,
code configuration…
 C# provides preprocessor directives that
serve a number of functions
 Unlike C++, there is not a separate
preprocessor
◦ The “preprocessor” name is preserved only for
consistency with C++
 C++ preprocessor features removed include:
◦ #include: Not really needed with one-stop
programming; removal results in faster compilation
◦ Macro version of #define: removed for clarity
Directive Description
#define, #undef Define and undefine conditional symbols
#if, #elif, #else, #endif Conditionally skip sections of code
#error, #warning Issue errors and warnings
#region, #end Delimit outline regions
#line Specify line number
#define Debug
public class Debug {
[Conditional("Debug")]
public static void Assert(bool cond, String s) {
if (!cond) {
throw new AssertionException(s);
}
}
void DoSomething() {
...
// If Debug is not defined, the next line is
// not even called
Assert((x == y), “X should equal Y”);
...
}
}
 By the way, assertions are an incredible way
to improve the quality of your code
 An assertion is essentially a unit test built
right into your code
 You should have assertions to test
preconditions, postconditions and invariants
 Assertions are only enabled in debug builds
 Your code is QA‟d every time it runs
 Programmers don‟t like to document code, so we
need a way to make it easy for them to produce
quality,
up-to-date documentation
 C# lets you embed XML comments that document
types, members, parameters, etc.
◦ Denoted with triple slash: ///
 XML document is generated when code is compiled
with /doc argument
 Comes with predefined XML schema, but you can
add your own tags too
◦ Some are verified, e.g. parameters, exceptions, types
XML Tag Description
<summary>, <remarks> Type or member
<param> Method parameter
<returns> Method return value
<exception> Exceptions thrown from method
<example>, <c>, <code> Sample code
<see>, <seealso> Cross references
<value> Property
<paramref> Use of a parameter
<list>, <item>, ... Formatting hints
<permission> Permission requirements
 Developers sometime need total control
◦ Performance extremes
◦ Dealing with existing binary structures
◦ Existing code
◦ Advanced COM support, DLL import
 C# allows you to mark code as unsafe,
allowing
◦ Pointer types, pointer arithmetic
◦ ->, * operators
◦ Unsafe casts
◦ No garbage collection
unsafe void Foo() {
char* buf = stackalloc char[256];
for (char* p = buf; p < buf + 256; p++) *p = 0;
...
}
 Lets you embed native C/C++ code
 Basically “inline C”
 Must ensure the GC doesn‟t move your data
◦ Use fixed statement to pin data
◦ Use stackalloc operator so memory is allocated
on stack, and need not be pinned
class FileStream: Stream {
int handle;
public unsafe int Read(byte[] buffer, int index,
int count) {
int n = 0;
fixed (byte* p = buffer) {
ReadFile(handle, p + index, count, &n, null);
}
return n;
}
[dllimport("kernel32", SetLastError=true)]
static extern unsafe bool ReadFile(int hFile,
void* lpBuffer, int nBytesToRead,
int* nBytesRead, Overlapped* lpOverlapped);
}
C#ppt

Contenu connexe

Tendances

ES6 presentation
ES6 presentationES6 presentation
ES6 presentationritika1
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introductionPeter Gfader
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages mohamed drahem
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparisonKaty Slemon
 
Null safety in dart and flutter , the whole story!
Null safety in dart and flutter , the whole story!Null safety in dart and flutter , the whole story!
Null safety in dart and flutter , the whole story!Ahmed Abu Eldahab
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in JavaJava2Blog
 

Tendances (20)

C# in depth
C# in depthC# in depth
C# in depth
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
.NET and C# introduction
.NET and C# introduction.NET and C# introduction
.NET and C# introduction
 
CI/CD with GitHub Actions
CI/CD with GitHub ActionsCI/CD with GitHub Actions
CI/CD with GitHub Actions
 
C#.NET
C#.NETC#.NET
C#.NET
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
.Net framework vs .net core a complete comparison
.Net framework vs .net core  a complete comparison.Net framework vs .net core  a complete comparison
.Net framework vs .net core a complete comparison
 
.Net
.Net.Net
.Net
 
Tomcat
TomcatTomcat
Tomcat
 
Null safety in dart and flutter , the whole story!
Null safety in dart and flutter , the whole story!Null safety in dart and flutter , the whole story!
Null safety in dart and flutter , the whole story!
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React Native
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 

Similaire à C#ppt

Understanding C# in .NET
Understanding C# in .NETUnderstanding C# in .NET
Understanding C# in .NETmentorrbuddy
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
csharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxcsharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxPoornima E.G.
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01Zafor Iqbal
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 

Similaire à C#ppt (20)

Understanding C# in .NET
Understanding C# in .NETUnderstanding C# in .NET
Understanding C# in .NET
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
C# Unit 1 notes
C# Unit 1 notesC# Unit 1 notes
C# Unit 1 notes
 
C#
C#C#
C#
 
csharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptxcsharp_dotnet_adnanreza.pptx
csharp_dotnet_adnanreza.pptx
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
1.Philosophy of .NET
1.Philosophy of .NET1.Philosophy of .NET
1.Philosophy of .NET
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
C#2
C#2C#2
C#2
 
C#.net Evolution part 1
C#.net Evolution part 1C#.net Evolution part 1
C#.net Evolution part 1
 
iOS Application Development
iOS Application DevelopmentiOS Application Development
iOS Application Development
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
cs8251 unit 1 ppt
cs8251 unit 1 pptcs8251 unit 1 ppt
cs8251 unit 1 ppt
 

Dernier

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 

Dernier (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 

C#ppt

  • 1.
  • 2.  C# (pronounced CSharp) is no doubt the language of choice in .NET Environment.  It is an Object Oriented Programming Language has its core and many features similar to C++ and Java.  But it is easy to learn and to develop as compare to C++ and Java.  Its design is more in tune with modern developer tools than both of those other languages, and it has been designed to provide.  simultaneously, the ease of use of Visual Basic and the high-performance, low-level memory access of C++,if required.  Automatic cleanup of dynamically allocated memory.  The facility to mark classes or methods with user-defined attributes. This can be useful for documentation and can have some effects on compilation  Full access to the .NET base class library, as well as easy access to the Windows API  Pointers and direct memory access are available if required, but the language has been designed in such a way that you can work without them in almost all cases.  Support for properties and events in the style of Visual Basic.  C# can be used to write ASP.NET dynamic web pages and XML Web services.
  • 3. Program File 2.cs File n.cs Namespace B {….} Namespace C{…} Class 2 {….} Class n {…} File 1.cs Namespace A{…} Class 1{…}
  • 4.  Variable : It is a placeholder where it stores the specified data values and varies by requirement.  Rules:- These may start with alphabets are with underscore(„_‟) symbol  These may contain numeric's also.  It won‟t allow special characters like @,#,!,$,% etc.  You can‟t use keywords as Variables.  Ex: xyz,_abc,abc123, etc.
  • 5.  In .NET Environment CLR categories all DataTypes into two ways, those are  1.Value Type: The DataTypes which are derived from system level are called as “ValueTypes”.  These are stored in Stack memory  Ex: int,float,bool,double, etc.  2.ReferenceTypes: The DataTypes which are derived from class level are called as “RefernceTypes”.  These are stored in Heap Memory.  Ex: class, object, string, etc.
  • 6.  These are the key notations pre defined by CLR in .NET Environment.  These contains a special meaning to use in Program.  You can‟t use these as keywords.  Ex: class, interface, int, static, abstract, etc.
  • 7.  Comments ◦ Comments can be created using //… ◦ Multi-lines comments use /* … */ ◦ Comments are ignored by the compiler ◦ Used only for human readers  Namespaces ◦ Groups related C# features into a categories ◦ Allows the easy reuse of code ◦ Many namespaces are found in the .NET framework library ◦ Must be referenced in order to be used  White Space ◦ Includes spaces, newline characters and tabs
  • 8.  These are special symbols which will operate on values or variables.  These symbols specifies a action to be done, that is already known to compiler.  It support a set of Operators those are  Arithmetic operators  Conditional operators  Bitwise operators  Relational operators  Logical operators  Assignment operators  Increment and decrement operators  Special operators[ comma(,), sizeof(). [+,-,*,/,%] [condition ? true, false: ] [&, |,^,<<,>>,~] [==,<=,>=,>,<,!=] [&&,||,!] [=,+=,/=,-=,*=] [++,--]
  • 9.  These are basic building block of program that controls flow of program.  It executes a particular block based on Boolean condition .  C# comes with set of conditional statements, are If statements If else Nested if Switch Ternary statements. If(condition) {body} Ex: if(m%2==0) {“even number”} Ex: if(m%2==0) {“even number”} else {“Odd number”} switch(condition) { Case”1”://do //break; case “n”: //do Break; } If(condition) {body} Else {body}
  • 10.  break ◦ Exit inner-most loop  continue ◦ End iteration of inner-most loop  goto <label> ◦ Transfer execution to label statement  return [<expression>] ◦ Exit a method  throw ◦ Used in exception handling
  • 11.  These statements should control the flow of program, to repeat the particular action.  C# provides a set of control statements those are Initialization; While(condition) {//body; //inc or dec; } Initialization; Do { //body; //inc or dec; } While(condition); while: do while: for loop for(initialization ;condition ;inc/dec) { //body; } foreach foreach( data type variable name in collection name) { //body; } • foreach is new control statement •In c# which is used to operate on collection •It won‟t take any starts or ends and conditions
  • 12.  Array is a collection of similar data types.  It stores continuously in memory with zero based index values.  Types: 1.1D Array 2. Multi Dimensional Array 3. Jagged Array  1D Array: contains only single dimension of elements . Syntax: Type[] name; Declaration: Type[] name =new type[size]; Initialization: type[] name=new type[size]{v1,v2,..V n} Multi dimension array contain both rows and columns. Syntax: type[ , ]=new type[r size, c size]; Initialization: int[] arr=new int[2,3] { {1,2,3}, {4,5,6} }
  • 13.  Jagged Array: An Array of Arrays is called as “jagged Array”.  New array type introduced in C#.  Syntax: type[ ][ ] name=new type[ size] [ ]; Ex: int [ ][ ] myarray =new int[3] [ ]; Initialization: int[ ][ ] myarray=new int[3] [ ]; myarray[0]=new int[ size] {v1,v2…} myarray[1]=new int[ size] {v1,v2…} myarray[2]=new int[ size] {v1,v2…} •In c# array class was contain so many in built methods and properties for simplifying operations on arrays. •Like Array.Sort() ,Array.Reverse() etc.
  • 14.  Objects, instances and classes  Identity ◦ Every instance has a unique identity, regardless of its data  Encapsulation ◦ Data and function are packaged together ◦ Information hiding ◦ An object is an abstraction  User should NOT know implementation details
  • 15.  Properties: ◦ Breed ◦ Age ◦ Color ◦ Weight ◦ Shot Record  Methods: ◦ sit() ◦ layDown() ◦ eat() ◦ run()  A Class in OOP encapsulates properties and methods  A class, like a blueprint, is used to make instances or objects
  • 16.  Property Values: ◦ Name: Kazi ◦ Breed: Border Collie ◦ Age: 2 years ◦ Color: Black and White ◦ Weight: 23 Pounds  Properties:  Name Breed  Age  Color  Weight Create Instance  Methods:  Sit  Play Dead  Eat  Run  Methods:  Sit  Play Dead  Eat  Run
  • 17.  Use the new operator to create an object of a class  Properties and methods of the object can now be accessed Button MyButton = new Button(); Button.Text=“ Click Me”;
  • 18.  Classes have the following modifier: ◦ new* ◦ public ◦ protected* ◦ internal ◦ private* ◦ abstract ◦ sealed ◦ static ** * only usable on nested classes ** C# 2.0 Defaults: internal (for non- nested classes) private (for nested classes) non-abstract non-sealed non-static
  • 19.  public ◦ Anyone can access  protected ◦ Private to containing type and any derived types  internal ◦ Public inside of the assembly (the .exe or .dll) no one else may access  protected internal ◦ Public inside of the assembly or private to types derived from the containing class  private (default) ◦ Access limited to the containing type
  • 20. Polymorphism The ability to use an object without knowing its precise type Three main kinds of polymorphism •Inheritance •Interfaces •Late binding Dependencies For reuse and to facilitate development, systems should be loosely coupled Dependencies should be minimized
  • 21.  In OOP, types are arranged in a hierarchy ◦ A Base class is the parent class ◦ A Derived class is the child class  Object is the Base class of all other types in C#  C# only allows single inheritance of classes  C# allows multiple inheritance of interfaces Object Animal Dog
  • 22.  An interface defines a contract ◦ An interface is a type ◦ Includes methods, properties, indexers, events ◦ Any class or struct implementing an interface must support all parts of the contract  Interfaces provide no implementation ◦ When a class or struct implements an interface it must provide the implementation  Interfaces provide polymorphism ◦ Many classes and structs may implement a particular interface
  • 23. public interface IDelete { void Delete(); } public class TextBox : IDelete { public void Delete() { ... } } public class Car : IDelete { public void Delete() { ... } } TextBox tb = new TextBox(); IDelete iDel = tb; iDel.Delete(); Car c = new Car(); iDel = c; iDel.Delete();
  • 24. interface IControl { void Paint(); } interface IListBox: IControl { void SetItems(string[] items); } interface IComboBox: ITextBox, IListBox { }  Classes and structs can inherit from multiple interfaces  Interfaces can inherit from multiple interfaces
  • 25. interface IControl { void Delete(); } interface IListBox: IControl { void Delete(); } interface IComboBox: ITextBox, IListBox { void IControl.Delete(); void IListBox.Delete(); }  If two interfaces have the same method name, you can explicitly specify interface + method name to disambiguate their implementations
  • 26.  Both are user-defined types  Both can implement multiple interfaces  Both can contain ◦ Data  Fields, constants, events, arrays ◦ Functions  Methods, properties, indexers, operators, constructors ◦ Type definitions  Classes, structs, enums, interfaces, delegates
  • 27. Class Struct Reference type Value type Can inherit from any non-sealed reference type No inheritance (inherits only from System.ValueType) Can have a destructor No destructor Can have user-defined parameterless constructor No user-defined parameterless constructor
  • 28. public class Car : Vehicle { public enum Make { GM, Honda, BMW } Make make; string vid; Point location; Car(Make m, string vid; Point loc) { this.make = m; this.vid = vid; this.location = loc; } public void Drive() { Console.WriteLine(“vroom”); } } Car c = new Car(Car.Make.BMW, “JF3559QT98”, new Point(3,7)); c.Drive();
  • 29. public struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point p = new Point(2,5); p.X += 100; int px = p.X; // px = 102
  • 30.  By default, members are per instance ◦ Each instance gets its own fields ◦ Methods apply to a specific instance  Static members are per type ◦ Static methods can‟t access instance data ◦ No this variable in static methods  Don‟t abuse static members ◦ They are essentially object-oriented global data and global functions
  • 31.  An abstract class is one that cannot be instantiated  Intended to be used as a base class  May contain abstract and non-abstract function members  Similar to an interface  Cannot be sealed
  • 32.  A sealed class is one that cannot be used as a base class  Sealed classes can‟t be abstract  All structs are implicitly sealed  Why seal a class? ◦ To prevent unintended derivation ◦ Code optimization  Virtual function calls can be resolved at compile-time
  • 33. class Person { string name; public Person(string name) { this.name = name; } public void Introduce(Person p) { if (p != this) Console.WriteLine(“Hi, I‟m “ + name); } }  The this keyword is a predefined variable available in non-static function members ◦ Used to access data and function members unambiguously
  • 34. class Shape { int x, y; public override string ToString() { return "x=" + x + ",y=" + y; } } class Circle : Shape { int r; public override string ToString() { return base.ToString() + ",r=" + r; } }  The base keyword is used to access class members that are hidden by similarly named members of the current class
  • 35.  Similar to a const, but is initialized at run-time in its declaration or in a constructor ◦ Once initialized, it cannot be modified  Differs from a constant ◦ Initialized at run-time (vs. compile-time)  Don‟t have to re-compile clients ◦ Can be static or per-instance public class MyClass { public static readonly double d1 = Math.Sin(Math.PI); public readonly string s1; public MyClass(string s) { s1 = s; } }
  • 36. public class Button: Control { private string caption; public string Caption { get { return caption; } set { caption = value; Repaint(); } } } Button b = new Button(); b.Caption = "OK"; String s = b.Caption;  A property is a virtual field  Looks like a field, but is implemented with code  Can be read-only, write-only, or read/write
  • 37. public class ListBox: Control { private string[] items; public string this[int index] { get { return items[index]; } set { items[index] = value; Repaint(); } } } ListBox listBox = new ListBox(); listBox[0] = "hello"; Console.WriteLine(listBox[0]);  An indexer lets an instance behave as a virtual array  Can be overloaded (e.g. index by int and by string)  Can be read-only, write-only, or read/write
  • 38.  All code executes in a method ◦ Constructors, destructors and operators are special types of methods ◦ Properties and indexers are implemented with get/set methods  Methods have argument lists  Methods contain statements  Methods can return a value ◦ Only if return type is not void
  • 39.  By default, data is passed by value  A copy of the data is created and passed to the method  For value types, variables cannot be modified by a method call  For reference types, the instance can be modified by a method call, but the variable itself cannot be modified by a method call
  • 40. void RefFunction(ref int p) { p++; } int x = 10; RefFunction(ref x); // x is now 11  The ref modifier causes arguments to be passed by reference  Allows a method call to modify a variable  Have to use ref modifier in method definition and the code that calls it  Variable has to have a value before call
  • 41. void OutFunction(out int p) { p = 22; } int x; OutFunction(out x); // x is now 22  The out modifier causes arguments to be passed out by reference  Allows a method call to initialize a variable  Have to use out modifier in method definition and the code that calls it  Argument has to have a value before returning
  • 42. void Print(int i); void Print(string s); void Print(char c); void Print(float f); int Print(float f); // Error: duplicate signature  A type may overload methods, i.e. provide multiple methods with the same name  Each must have a unique signature  Signature is based upon arguments only, the return value is ignored
  • 43. int Sum(params int[] intArr) { int sum = 0; foreach (int i in intArr) sum += i; return sum; } int sum = Sum(13,87,34);  Methods can have a variable number of arguments, called a parameter array  params keyword declares parameter array  Must be last argument
  • 44. class Foo { public void DoSomething(int i) { ... } } Foo f = new Foo(); f.DoSomething();  Methods may be virtual or non-virtual (default)  Non-virtual methods are not polymorphic ◦ They cannot be overridden  Non-virtual methods cannot be abstract
  • 45.  Defined in a base class  Can be overridden in derived classes ◦ Derived classes provide their own specialized implementation  May contain a default implementation ◦ Use abstract method if no default implementation  A form of polymorphism  Properties, indexers and events can also be virtual
  • 46. class Shape { public virtual void Draw() { ... } } class Box : Shape { public override void Draw() { ... } } class Sphere : Shape { public override void Draw() { ... } } void HandleShape(Shape s) { s.Draw(); ... } HandleShape(new Box()); HandleShape(new Sphere()); HandleShape(new Shape());
  • 47.  An abstract method is virtual and has no implementation  Must belong to an abstract class  Intended to be implemented in a derived class
  • 48. abstract class Shape { public abstract void Draw(); } class Box : Shape { public override void Draw() { ... } } class Sphere : Shape { public override void Draw() { ... } } void HandleShape(Shape s) { s.Draw(); ... } HandleShape(new Box()); HandleShape(new Sphere()); HandleShape(new Shape()); // Error!
  • 49.  Instance constructors are special methods that are called when a class or struct is instantiated  Performs custom initialization  Can be overloaded  If a class doesn‟t define any constructors, an implicit parameterless constructor is created  Cannot create a parameterless constructor for a struct ◦ All fields initialized to zero/null
  • 50. class B { private int h; public B() { } public B(int h) { this.h = h; } } class D : B { private int i; public D() : this(24) { } public D(int i) { this.i = i; } public D(int h, int i) : base(h) { this.i = i; } }  One constructor can call another with a constructor initializer  Can call this(...) or base(...)  Default constructor initializer is base()
  • 51.  A static constructor lets you create initialization code that is called once for the class  Guaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct is accessed  No other guarantees on execution order  Only one static constructor per type  Must be parameterless
  • 52. class Foo { ~Foo() { Console.WriteLine(“Destroyed {0}”, this); } }  A destructor is a method that is called before an instance is garbage collected  Used to clean up any resources held by the instance, do bookkeeping, etc.  Only classes, not structs can have destructors
  • 53.  Unlike C++, C# destructors are non- deterministic  They are not guaranteed to be called at a specific time  They are guaranteed to be called before shutdown  Use the using statement and the IDisposable interface to achieve deterministic finalization
  • 54. class Car { string vid; public static bool operator ==(Car x, Car y) { return x.vid == y.vid; } }  User-defined operators  Must be a static method
  • 55. + - ! ~ true false ++ --  Overloadable unary operators  Overloadable binary operators + - * / ! ~ % & | ^ == != << >> < > <= >=
  • 56.  No overloading for member access, method invocation, assignment operators, nor these operators: sizeof, new, is, as, typeof, checked, unchecked, &&, ||, and ?:  The && and || operators are automatically evaluated from & and |  Overloading a binary operator (e.g. *) implicitly overloads the corresponding assignment operator (e.g. *=)
  • 57.  The is operator is used to dynamically test if the run-time type of an object is compatible with a given type static void DoSomething(object o) { if (o is Car) ((Car)o).Drive(); }  Don’t abuse the is operator: it is preferable to design an appropriate type hierarchy with polymorphic methods
  • 58.  The as operator tries to convert a variable to a specified type; if no such conversion is possible the result is null static void DoSomething(object o) { Car c = o as Car; if (c != null) c.Drive(); }  More efficient than using is operator: test and convert in one operation  Same design warning as with the is operator
  • 59.  The typeof operator returns the System.Type object for a specified type  Can then use reflection to dynamically obtain information about the type Console.WriteLine(typeof(int).FullName); Console.WriteLine(typeof(System.Int).Name); Console.WriteLine(typeof(float).Module); Console.WriteLine(typeof(double).IsPublic); Console.WriteLine(typeof(Car).MemberType);
  • 60.  A delegate is a reference type that defines a method signature  A delegate instance holds one or more methods ◦ Essentially an “object-oriented function pointer” ◦ Methods can be static or non-static ◦ Methods can return a value  Provides polymorphism for individual functions  Foundation for event handling
  • 61. delegate double Del(double x); // Declare static void DemoDelegates() { Del delInst = new Del(Math.Sin); // Instantiate double x = delInst(1.0); // Invoke }
  • 62.  A delegate can hold and invoke multiple methods ◦ Multicast delegates must contain only methods that return void, else there is a run-time exception  Each delegate has an invocation list ◦ Methods are invoked sequentially, in the order added  The += and -= operators are used to add and remove delegates, respectively  += and -= operators are thread-safe
  • 63. delegate void SomeEvent(int x, int y); static void Foo1(int x, int y) { Console.WriteLine("Foo1"); } static void Foo2(int x, int y) { Console.WriteLine("Foo2"); } public static void Main() { SomeEvent func = new SomeEvent(Foo1); func += new SomeEvent(Foo2); func(1,2); // Foo1 and Foo2 are called func -= new SomeEvent(Foo1); func(2,3); // Only Foo2 is called }
  • 64.  Could always use interfaces instead of delegates  Interfaces are more powerful ◦ Multiple methods ◦ Inheritance  Delegates are more elegant for event handlers ◦ Less code ◦ Can easily implement multiple event handlers on one class/struct
  • 65.  Event handling is a style of programming where one object notifies another that something of interest has occurred ◦ A publish-subscribe programming model  Events allow you to tie your own code into the functioning of an independently created component  Events are a type of “callback” mechanism
  • 66.  Events are well suited for user-interfaces ◦ The user does something (clicks a button, moves a mouse, changes a value, etc.) and the program reacts in response  Many other uses, e.g. ◦ Time-based events ◦ Asynchronous operation completed ◦ Email message has arrived ◦ A web session has begun
  • 67.  C# has native support for events  Based upon delegates  An event is essentially a field holding a delegate  However, public users of the class can only register delegates ◦ They can only call += and -= ◦ They can‟t invoke the event‟s delegate  Multicast delegates allow multiple objects to register with the same event
  • 68.  Define the event signature as a delegate  Define the event and firing logic public delegate void EventHandler(object sender, EventArgs e); public class Button { public event EventHandler Click; protected void OnClick(EventArgs e) { // This is called when button is clicked if (Click != null) Click(this, e); } }
  • 69.  Define and register an event handler public class MyForm: Form { Button okButton; static void OkClicked(object sender, EventArgs e) { ShowMessage("You pressed the OK button"); } public MyForm() { okButton = new Button(...); okButton.Caption = "OK"; okButton.Click += new EventHandler(OkClicked); } }
  • 70.  Anonymous methods let you declare a method body without giving it a name.  Behind the scenes, they exist as 'normal' methods;  Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword. class Program { static void Main(string[] args) { new ShoppingCart().Process( new Func<bool,int>(delegate(bool x){ return x ? 10 : 5; } )); } } The true power of anonymous methods can be seen when using .NET methods that expect delegates as parameters and when responding to events. Previously, you had to create a method for every possible action you wanted to take.
  • 71.  Lambda expression is an inline delegate introduced with C # 3.0 language.  It‟s a concise way to represent an anonymous method.  Lambda expression uses the type inference feature of C# 3.0 Both anonymous methods and Lambda expressions allow you define the method implementation inline, however, an anonymous method explicitly requires you to define the parameter types and the return type for a method. Parameter=> execution code public static void SimpleLambdExpression() { List<int> numbers = new List<int>{1,2,3,4,5,6,7}; var evens = numbers.FindAll(n => n % 2 == 0); var evens2 = numbers.FindAll((int n) => { return n % 2 == 0; }); ObjectDumper.Write(evens); ObjectDumper.Write(evens2); }
  • 72.  Strongly typed ◦ No implicit conversions to/from int ◦ Operators: +, -, ++, --, &, |, ^, ~  Can specify underlying type ◦ Byte, short, int, long enum Color: byte { Red = 1, Green = 2, Blue = 4, Black = 0, White = Red | Green | Blue, }
  • 73.  Begin with a simple array of, say, Customers. Customer[] customers = new Customer[30]; customers[0] = new Customer(…); … customers[29] = new Customer(…); A C# language extension: Use SQL-like syntax in C#. LINQ  Find the names of all London customers: List<string> londoners = new List<string>(); foreach (Customer c in customers) { if (c.City == “London”) { londoners.add(c.Name); } }
  • 74. string[] londoners = from c in customers where c.City == “London” select c.Name; Declarative! SQL-like! No loops!
  • 75.  It‟s often necessary to associate information (metadata) with types and members, e.g. ◦ Documentation URL for a class ◦ Transaction context for a method ◦ XML persistence mapping ◦ COM ProgID for a class  Attributes allow you to decorate a code element (assembly, module, type, member, return value and parameter) with additional information
  • 76.  Attributes are superior to the alternatives ◦ Modifying the source language ◦ Using external files, e.g., .IDL, .DEF  Attributes are extensible ◦ Attributes allow to you add information not supported by C# itself ◦ Not limited to predefined information  Built into the .NET Framework, so they work across all .NET languages ◦ Stored in assembly metadata
  • 77. Attribute Name Description Browsable Should a property or event be displayed in the property window Serializable Allows a class or struct to be serialized Obsolete Compiler will complain if target is used ProgId COM Prog ID Transaction Transactional characteristics of a class  Some predefined .NET Framework attributes
  • 78.  Attributes can be ◦ Attached to types and members ◦ Examined at run-time using reflection  Completely extensible ◦ Simply a class that inherits from System.Attribute  Type-safe ◦ Arguments checked at compile-time  Extensive use in .NET Framework ◦ XML, Web Services, security, serialization, component model, COM and P/Invoke interop, code configuration…
  • 79.  C# provides preprocessor directives that serve a number of functions  Unlike C++, there is not a separate preprocessor ◦ The “preprocessor” name is preserved only for consistency with C++  C++ preprocessor features removed include: ◦ #include: Not really needed with one-stop programming; removal results in faster compilation ◦ Macro version of #define: removed for clarity
  • 80. Directive Description #define, #undef Define and undefine conditional symbols #if, #elif, #else, #endif Conditionally skip sections of code #error, #warning Issue errors and warnings #region, #end Delimit outline regions #line Specify line number
  • 81. #define Debug public class Debug { [Conditional("Debug")] public static void Assert(bool cond, String s) { if (!cond) { throw new AssertionException(s); } } void DoSomething() { ... // If Debug is not defined, the next line is // not even called Assert((x == y), “X should equal Y”); ... } }
  • 82.  By the way, assertions are an incredible way to improve the quality of your code  An assertion is essentially a unit test built right into your code  You should have assertions to test preconditions, postconditions and invariants  Assertions are only enabled in debug builds  Your code is QA‟d every time it runs
  • 83.  Programmers don‟t like to document code, so we need a way to make it easy for them to produce quality, up-to-date documentation  C# lets you embed XML comments that document types, members, parameters, etc. ◦ Denoted with triple slash: ///  XML document is generated when code is compiled with /doc argument  Comes with predefined XML schema, but you can add your own tags too ◦ Some are verified, e.g. parameters, exceptions, types
  • 84. XML Tag Description <summary>, <remarks> Type or member <param> Method parameter <returns> Method return value <exception> Exceptions thrown from method <example>, <c>, <code> Sample code <see>, <seealso> Cross references <value> Property <paramref> Use of a parameter <list>, <item>, ... Formatting hints <permission> Permission requirements
  • 85.  Developers sometime need total control ◦ Performance extremes ◦ Dealing with existing binary structures ◦ Existing code ◦ Advanced COM support, DLL import  C# allows you to mark code as unsafe, allowing ◦ Pointer types, pointer arithmetic ◦ ->, * operators ◦ Unsafe casts ◦ No garbage collection
  • 86. unsafe void Foo() { char* buf = stackalloc char[256]; for (char* p = buf; p < buf + 256; p++) *p = 0; ... }  Lets you embed native C/C++ code  Basically “inline C”  Must ensure the GC doesn‟t move your data ◦ Use fixed statement to pin data ◦ Use stackalloc operator so memory is allocated on stack, and need not be pinned
  • 87. class FileStream: Stream { int handle; public unsafe int Read(byte[] buffer, int index, int count) { int n = 0; fixed (byte* p = buffer) { ReadFile(handle, p + index, count, &n, null); } return n; } [dllimport("kernel32", SetLastError=true)] static extern unsafe bool ReadFile(int hFile, void* lpBuffer, int nBytesToRead, int* nBytesRead, Overlapped* lpOverlapped); }