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

The C# Concepts

Agenda
NameSpaces Classes & Types

Inheritance
Modifiers Interfaces Generics LINQ

C# in .NET
C# is a new programming language. It has 2 significance.
(1)It has a feature-rich platform for development, deployment, and execution of distributed applications.

It was designed & targeted for use with MS .NET Framework. (2)It is a lnguage based on the modern O-O design methodology

Common Language Runtime


The .NET Framework has its own runtime execution environment known as CLR or .NET runtime. The Source code developed in C# under .NET Framework needs to be compiled.Under .NET platform compilation occurs at 2 steps: (1) Compilation of source code to IL. (2) Compilation of IL to platform specific code by the CLR. Significant advantages of using this compilation pattern Platform Independence Performance Improvement Language Interoperability Important Features of Intermediate Languages Object orientation & Interfaces Strong distinction between Value & Reference Types. Strong Data typing Error handling Using Exceptions Use of Attributes

Features of Intermediate Language -I


Object Orientation & Interfaces Programming methodology implemented within IL : Classic O-O with (+) Single Implementation Inheritance of Classes. Interfaces : Interfaces provide a contract that classes used within that interface must provide implementation of methods & properties specified by it. Langauage Interoperability :Classes written in one language can interact with the classes written in another language.It was implemented supporting the following featues : (1) Inheritance : Class written in one language can inherit freom class written in another language. (2) The class can contain an instance of another class , irrespective of their languages.

(3)An object can directly call methods against another object written in another language
(4) Objects / Reference to objects can be passed around between methods. (5) When calling methods between languages one can step between methods calls in the debugger , even when this means stepping between source code written in different languages.

Features of Intermediate Language - II


Strong distinction between Value & Reference Types
Value types are those data types for which a variable directly stores its data, in a memory area known as Stack. Reference Types are those data types for which a variable store the address at which the data can be found, in a memory location called as heap.

Features of Intermediate Language - III


Strong data Typing All variables are of a specific data types.

Features of Intermediate Language - IV


Error Handling & Exceptions Certain area of code are designated as exception Handler routines , with each routine dealing with a particular error condition. The architecture of Exception Handling provides a convenient means to pass an object containing a precise details of the exception condition to an exception handling routine.zthe object might include an appropriate message for the userand details of exactly where in the code the exception was detected. .NET provides a set of Classes that represents Exceptions , and the language interoperability to allow the exception-thrown-objects to be interpreted by the exception-handling routines , irrespective of the language of the exceptionhandling codes.

C# handles exception using try(), catch(), finally() blocks of code.

Features of Intermediate Language - V


Use of Attributes Attributes : provides extra information, that is used by compiler, about certain item in the program . In .NET prgrammer can define their own attributes in the source code. It is placed with the metadata for corresponding methods or data types. Reflection Technology is used to define attribute based programming tasks. Attributes can be defined in source code of one programming language and can be used in the source code of another programming language..

Assemblies- I
An assembly is the logical unit that contains compiled code for .NET platform. . They contain the metadata that describes the data types & methods defined in program executable code. It also contain metadata, data about the assembly, within an assembly area known as Manifest. Manifest allows checks for Assembly Version & on its integerity. An assembly is self describing and can be stored in more than one file. In this case there will be one main file that will contain an entry point and the description about the other files in the assembly. If any of the other files is tampered or replaced, assembly will detect it and will refuse to load , thus maintaining datacode- synchronisation.

Assemblies are of two types: private & shared 3.1 Private Assembly : They are created for use within a particular application only and are shipped with the application. 3.2 Shared Assembly : They are common Libraries to be used by a number of applications.

Assemblies - II
Shared Assembly : They are common Libraries to be used by a number of applications. Risks associated with shared assemblies are: Name collision : assembly created by 2 different companies may have same name for their data types , thus creating name conflict wthin the development code using these assemblies. -- To resolve name conflict , shared assemblies are given a name,known as strong names , based on private data cryptography. --Strong names are Unique and must be quoted by application that reference a shared library.

Installation :Shared Libraries are Installed by .NET supplied utilities into GAC(Global Assembly cache). GAC implements folder Hierarchy to maintain assembly Integrity. Versionong is maintained by adding Version Information in the Assembly Manifest and thus allowing side-by-side installations.

.Net Framework Classes


They are massive collection of managed code classesThese classes uses the same object model that IL use based on single Inheritance.That is we can instantiate any classes from .Net Framework Base class or derive user-created classes from them.

NameSpaces
Namespaces are used in .NET to avoid class-name clashes. It is a group of data types.

If a namespace is not explicitly assigned while creating a class then it is added to the nameless Global namespace.
MS recommends to use use atleast 2 nested namespaces: First Representing name of the company

Second representing the name of the technology or the name of the software package.Ex: YourCompanyname.Inventory.CreateProductList

Creating .NET Applications using C#


ASP.NET Applications. Web Forms

Web Server Controls : They are the XML tags in the ASP.NET namespace that a Web browser dynamically transforms into HTML and client-side scripts when a page is requested.
XML Web Services:

Creating Windows Forms


.NET MVC2 Web-based Application Windows Controls

Windows Services
WCF: Provides ability to build service one time and expose this service in no. of ways(under different protocols) by making changes with the configuration files.WCF is a powerful way of connecting disparate system.

Classes & Structs


Classes & Structs : They are Templates from which we create objects. Both use the keyword new to declare an instance. Structs : Structs are Value Types stored on the Stack within memory. Structs do not support Inheritance.

Structs are used for smaller data types for performnce reasons
Struct keyword is used to declare structs. ex: struct Customer { public int CustomerID public string CustomerName } Classes : Classes are Reference Types stored on Heap within memory. Classes support Inheritance. Classes are used to store complex & large data types

class keyword is used to declare classes. ex : class Customer {


}

public int CustomerID public string CustomerName

More on Classes - I
Data & Function within a class are known as classs member Classes can be declared as public, : class member is visible to class , any derived class and instance of the class private:class member is visible to class , but not to any derived class and instance of the class

protected : class member is visible only to class , any derived class and not to instance of the class)
Data Members : contain data for the class Fields ; any variables associated with the class. Constants: any variables associated with the class declared with keyword const

Events : allow an object to notify a caller when something noteworthy changes.


Function Members : provides functionality for manipulating the data in the class. Methods : functions associated with the class. can be declared as instance methods, static methods Properties : functions implementing read & write operations with the class data. C# : get; set; Constructors : called automatically when object is instantiated.have same name as the class name, can be overloaded, do not have a return type, used for initializing the values of fields. Finalizers. : called when an object is no longer needed, same name as classs name but starting with a (~).CL in .NET automatically handles garbage collection.

More on Classes - II
FUNCTION MEMBERS : provides functionality for manipulating the data in the class. Operators : C# allows pre-defined operators to work differently within a class, i.e., implements Operator Overloading functionality. Indexers:Allows the object to be indexed as array or collection. METHODS Declaring Methods : [public/private/protected] return_type MethodName ([parameters]) {// body of method} Invoking Methods: classname.methodname();

Passing Parameters to Methods:


(1) parameters are passed by value/ passed by reference (2) ref keyword is used pass value parameters by reference Ex: static void SomeFunction(int[] ints, ref int i) { ints[0]=100; i=100; // the change to i is persisted } Invoking method : SomeFunction(ints, ref i) Note : if reference type variables,such as class or array, is passed into the method, and the method uses the reference to change a value in that variable, the new value is reflected in the original reference type variable. A value must be initialized before it is passed into a Method, whether it is passed by value or reference.

More on Classes - III


METHODS (3) out Parameters : When a methods input argument is prefixed with out, then it can be passed without initializing. The variable is passed by reference, so the change in Method is persisted out keyword is used while defining & calling the method. Ex: Defining Method static void someFunction(out int i) { i=100;} Invoking Method int i ; someFunction(out i) Note : If the out parameter is not assigned a value within the Method , the Method will not compile. (4) Method Overloading: several versions of the method that have different signatures (different number or different types of parameters).

PROPERTIES Properties are Functions that can be accessed from Client code in a similar fashion as tht of a Field.C# provides a Read-Write properties on the Class. Defination : To define a property we in C# we use the following syntax: access_specifiers { get { // code} set { //code } } return_type propertyName

More on Classes IV
PROPERTIES
Defination : To define a property we in C# we use the following syntax: access_specifiers { get set } Get Accessor : It contains statements to read the values from the property. It takes no parameters and return same type as the declared Property. Set Accessor : It contains statements to write the values to the property. It takes no parameters but compiler assumes it takes one parameter, which is of same type as property , and refer to it as value. return_type { // code} { //code } propertyName

Example : To declare a property and apply length limit to it.


Public Class Test { Private String fName; Public String { get { set return fName;} { if value.length > 30 FirstName

// error statements else

fName=value;

}}

More on Classes IV
Read Only PROPERTIES
access_specifiers { get } return_type { // code} propertyName

contd

Defination : To define a read only property we omit set Accessor from the Property declaration

Write Only PROPERTIES Defination : To define a read only property we omit get Accessor from the Property declaration access_specifiers { set } return_type { // code} propertyName

Access Modifiers on Properties By default get & set property Accessor takes the access modifier of the Property.

But C# allows the get and set accessors to have different access modifiers than the property access modifiers.
One of the Accessor must follow the Access modifier of the property else compiler error will be generated.

More on Classes IV
Access Modifiers on Properties
Example : Public string Name { get { return name;} Private set { name= value;}

contd

More on Classes - V
CONSTRUCTORS We can define constructors to be private or protected. this keyword is used to distinguish member fields fom parameters of same name. If we do not supply a constructor , the compiler defines one behind the scenes.It is a basic constructor that initializes all the member fields by zeroing them all (zero for numeric data types, null for reference data types, false for booleans) Constructors can be overloaded, provided they have different signatures. Note : If you create a constructor with parameters, the compiler will not automatically supply a default one. Ex: defining a constructor public class MyNumber { private int number;

public MyNumber(int number)


{ } this.number=number; }

using a constructor in code ;

MyNumber numb = new myNumber(10);

// gives compilaton error.

More on Classes - VI
STATIC CONSTRUCTORS C# supports to create a static single, no-parameter , no-access- modifiers constructor for a class. A static constructor can access only static members of the class. It is not called by C# code but by the CLR whenever the class is loaded. Such constructor will be executed only once, before code makes any reference to the class/. In C# , it is usually seems to be executed immediately before the first call to any member of the class. It is possible to have static constructor and zero-parameter constructor in the same class.Here static constructor is executed when the class is first loaded and instance constructor is executed when the instance of the class is created. Other constructors are executed whenever an object of that class is created, Note : Static constructors are used in case when there are static fields or properties in a class, that needs to be initialized from external source before the class is first used. If any static fields have been given any default values , these will be allocated before the static constructor is called.

More on Classes - VI
STATIC CONSTRUCTORS Example : public class UserPreferences { public static readonly Color BackColor; static UserPreferences() { DateTime now = DateTime.Now; if (now.DayOfWeek == DayOfWeek.Saturday || now.DayOfWeek == DayOfWeek.Sunday) BackColor = Color.Green; else BackColor = Color.Red; } private UserPreferences() { /// } }

More on Classes - VI
Nested Constructors There are cases when we are using more than one constructors for a class and both constructors initialize the same fields. It would clearly be neater to place all the code in one place. C# has a special syntax known as a constructor initializer to allow this: Example : class Car { private string description; private uint nWheels; public Car(string description, uint nWheels) { this.description = descr this.nWheels = nWheels; } public Car(string description): this(description, 4) { } // etc } Usage : Car myCar=new Car(maruti Suzuki)

More on Classes - VI
ReadOnly Fields Requirements : There may be need of some variable whose value shouldnt be changd throughout the program execution, but where the value is not known until runtime. Also the field need to be constant but also need to carry out some calculations to determine its initial value.So we cannot use Constants. C# provides another type of variable that is useful in this scenario: the readonly field.

Rules:

Read-Only Fields of a Class can only be craeted inside the Constructor of the Class. Read-Only Fields can be static [universal for all the classes] or Instance R-O- Fields. Example : (1) Static R-O fields public class DocumentEditor { public static readonly uint MaxDocuments; static DocumentEditor() { MaxDocuments = DoSomethingToFindOutMaxNumber(); }} (2) public class Document { public readonly DateTime CreationDate; public Document() { // Read in creation date from file. Assume result is 1 Jan 2002 // but in general this can be different for different instances // of the class CreationDate = new DateTime(2002, 1, 1); } }

More on Classes - VII


PARTIAL CLASSES The partial keyword allows the class, struct, interface to span across multiple files. Typically a class reside in a single file. Partial classes are created in following cases - Multiple developers are parallely working on same class - In Situation when a code generator of some type is generating part of a class, and developer is extending the class in multiple files.

STATIC CLASSES Define a class with static keyword. The classes that contain only static methods and properties automatically becomes Static. An instrance of such classes can never be created.

OBJECT CLASSES
All .NET classes are derived from System.Object. If while defining a class we do not specify a base class , the compiler automatically assumes that it is derived from Object This Object class is supported with a number of public and protected Methods such as ToString(), Equals(), Finalize().

Partial Classes
//BigClassPart1.cs partial class TheBigClass { public void MethodOne() { } } //BigClassPart2.cs partial class TheBigClass { public void MethodTwo() { } } When the project that these two source files are part of is compiled, a single type called TheBig Class will be created with two methods, MethodOne() and MethodTwo().

Static Classes
A Class contains nothing but static methods and properties, the class itself can become static.

A static class is functionally the same as creating a class with a private static
constructor. An instance of the class can never be created. By using the static keyword, the compiler can help by checking that instance members are never accidentally added to the class. If they are, a compile error happens. This can help guarantee that an instance is never created. The syntax for a static class looks like this:
static class StaticUtilities
{ public static void HelperMethod() {

}
}

Extending the classes


If there is a need to add more functionality to an existing class but What if the source code isnt available? Extension methods can help by allowing you to change a class without requiring the source code for the class. Extension methods are static methods that can appear to be part of a class without actually being in the source code for the class.

contd
Example : Lets say that the Money class from the previous example needs to have a method AddToAmount(decimal amountToAdd). However, for whatever reason the original source for the assembly cannot be changed directly. Solution : All that you have to do is 1. create a static class and 2. add the AddToAmount method as a static method. Here is what the code would look like: public static class MoneyExtension { public static void AddToAmount(this Money money, decimal amountToAdd) { money.Amount += amountToAdd; } }

Note :For an extension method, (1) the first parameter is the type that is being extended preceded by the this keyword.
(2) This is what tells the compiler that this method is part of the Money type. In this example, Money is the type that is being extended. In the extension method you have access to all the public methods and properties of the type being extended.

More on Classes - VII


Anonymous Types Defination : An anonymous type is simply a nameless class that inherits from object. The definition of the class is inferred from the initializer, just as with implicitly typed Variables. Decalration : The var keyword used with the new keyword,creates anonymous types. Example : (1) If you need an object that contains a persons first, middle, and last name, the declaration would look like this:

var captain = new {FirstName = "James", MiddleName = "T", LastName = "Kirk"};


This would produce an object with FirstName, MiddleName, and LastName properties. If you were to create another object that looked like this:

var doctor = new {FirstName = "Leonard", MiddleName = "", LastName = "McCoy"};


the types of captain and doctor are the same. You could set captain = doctor, for example.

captain = doctor; (2) var captain = new {person.FirstName, person.MiddleName, person.LastName};

contd..
If the values that are being set come from another object, then the initializer can be abbreviated. If you already have a class that contains the properties FirstName, MiddleName, and LastName and you have an instance of that class with the instance name person, then the captain object could be initialized like this: var captain = new {person.FirstName, person.MiddleName, person.LastName}; The property names from the person object would be projected to the new object named captain. So the object named captain would have the FirstName, MiddleName, and LastName properties.

Structs
Defination for structs is also exactly the same as defination for classes. Example : The following code demonstrates a constructor and a property for a struct: struct Dimensions { public double Length; public double Width; public Dimensions(double length, double width) { Length=length; Width=width; } public double Diagonal { get { return Math.Sqrt(Length*Length + Width*Width); } } } Structs are value types, not reference types. This means they are stored either in the stack or inline (if they are part of another object that is stored on the heap) and have the same lifetime restrictions as the simple data types.

More on Structs
How Structs Differ From Classes Structs do not support inheritance. There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace. With a struct, you can specify how the fields are to be laid out in memory.

More on Structs
structs are Value Types Although structs are value types, you can often treat them syntactically in the same way as classes. For example, with the definition of the Dimensions class in the previous section, you could write: Dimensions point = new Dimensions(); point.Length = 3; point.Width = 6; Note that because structs are value types, the new operator does not work in the same way as it does for classes and other reference types. Instead of allocating memory on the heap, the new operator simply calls the appropriate constructor, according to the parameters passed to it, initializing all fields. Indeed, for structs it is perfectly legal to write: Dimensions point; point.Length = 3; point.Width = 6; If Dimensions was a class, this would produce a compilation error, because point would contain an uninitialized reference an address that points nowhere, so you could not start setting values to its fields. For a struct, however, the variable declaration actually allocates space on the stack for the entire struct, so its ready to assign values to. Note, however, that the following code would cause a compilation error, with the compiler complaining that you are using an uninitialized variable: Dimensions point; Double D = point.Length;

More on Structs
Rules for Defining Struct : Everything must be initialized before use. A struct is considered fully initialized when

(1) the new operator has been called against it, (2) The values have been individually assigned to all its fields. (3) A struct defined as a member field of a class is initialized by being zeroed-out automatically when the containing object is initialized.

Advantages & Disadvatages : On the positive side, allocating memory for structs is very fast because this takes place inline or on the stack. The same goes for removing structs when they go out of scope. On the negative side, whenever you pass a struct as a parameter or assign a struct to another struct (as in A=B, where A and B are structs), the full contents of the struct are copied, whereas for a class only the reference is copied. This will result in a performance loss that depends on the size of the struct, emphasizing the fact that structs are really intended for small data structures. Note, however, that when passing a struct as a parameter to a method, you can avoid this performance loss by passing it as a ref parameter in this case, only the address in memory of the struct will be passed in, which is just as fast as passing in a class.

More on Structs
Constructors for Structs: (1) Cannot define a constructor ftar Structs that takes no parameters.The default constructor, which initializes all fields to zero values, is always present implicitly, even if you supply other constructors that take parameters. Its also impossible to circumvent the default constructor by supplying initial values for fields. The following code will cause a compile-time error: struct Dimensions { public double Length = 1; // error. Initial values not allowed public double Width = 2; // error. Initial values not allowed }

Encapsulation
Defination : A OOPS Feature that groups the data along with the methods (or other functions) operating on that data . Implementation of Encapsulation within Classes in C# : Each Class can be defined with a list of Members 1. Data Members : Fields, Constants, 2. Function Members : Methods, Constructors, Destructors,Properties, Operators, Indexers

Member Accessors : Private. Public, Protected, Internal

Array of Classes
C# also provides functionality of creating Array of Reference types (Classes ) Syntax : <Classname>[] arrname= new <ClassName>[<length>]; Example : (1) Declaring an array of two Person elements :: Person[] myPersons = new Person[2]; You can allocate every element of the array by using an indexer starting from 0: myPersons[0] = new Person { FirstName="Ayrton", LastName="Senna" }; myPersons[1] = new Person {FirstName="Michael, LastName="Schumacher" };

Operator Overloading
Operator overloading enables you to use standard operators, such as +, >, and so on with classes that you design. This is called overloading because you are supplying your own implementations for these operators when used with specific parameter types, in much the same way that you overload methods by supplying different parameters for methods with the same name. Defining Operator Overloading into a Class (1) Operators may be overloaded by adding operator type members (which must be static) to a class. (2) specify number of operands dealing with and the types of these operands Ex: public static AddClass1 operator +(AddClass1 op1, AddClass1 op2) { AddClass1 returnVal = new AddClass1(); returnVal.val = op1.val + op2.val; return returnVal; }

Types of Inheritance
There are two types of Inheritance 1. Implementation inheritance : Derived class inherits all the base Classs Member fields and functions. 2. Interface Inheritance : Derived class inherits only the signature of base functions not its implementation.Useful in case when both base & deried class have common functions names but differs in functionality implemented.

IMPLEMENTATION INHERITANCE

Ex: public class DerivedClass : BaseClass, IInterface1, IInterface2


{ // etc/ }

Implementation of Inheritance - I
Casting It is safe to refer to derived class using base class reference.like ; But to refer base class from derived class needs type casting : Ex : BaseClass bobj=new DerivedClass(); DerivedClass dobj= bobj DerivedClass dobj=(DeivedClass) bobj; // error

//OK

Virtual Methods By declaring a Base Class function as virtual , it can be overridden in any derived classes. A base class property can also be declared as virtual. Ex: public class baseClass { public virtual string VirtualMethod() { //.. Code } } public class DerivedClass : baseClass { public override string VirtualMethod() {//.. Different code } } Code Snippet // refering BaseClass bobj=new DerivedClass(); //without virtual defination bobj.VirtualMethod(); //after virtual defination bobj.VirtualMethod();

//VirtualMethod of base class

//VirtualMethod of derived

class

Implementation of Inheritance - II
Hiding Methods If a method with same signature is declared in both derived and base class, but the methods are not declared as virtual or override resp, then the derived class version is said to hide base class version.And in this case the C# will throw the comile time warning if it declared without new keyword. Ex: public class baseClass { public string NewMethod() { //.. Code } } public class DerivedClass : baseClass { public string new NewMethod() {//.. Different code } } Code Snippet // refering BaseClass bobj=new DerivedClass(); //without New defination bobj.NewMethod(); //NewMethod of derived class //after declaring a NEW bobj.VirtualMethod();

//NewMethod of base

class

Implementation of Inheritance - III


Abstract Classes Instances of Abstract calsses can be created. Only classes can be derived from Abstract classes .Declared with keyword abstract. Methods within Abstract class can be declared as Abstract Abstract methods are implicitly virtual, derived class must declare and override them, and they do not contain any implementation so there is no method body. Ex: Banking Account. public abstract Class Account { public abstract bool WithDraw(double amt)

{
}

// no code }

Public SavingsAccount : Account { public abstract bool WithDraw(double amt) { // .. code } }

Code Snippet: Account S1=new Account(); //Error //OK SavingsAccount S1= new savingsAccount();

Modifiers
Modifiers are keywords applied to a data type or a member. Modifiers that indicates visiblity , such as private or public, of an item are called Visibility Modifiers Modifiers also indicates the nature of the item such as Virtual or abstract . Visibility Modifiers Public Protected Internal Private Protected internal Applies To Any Types/Members Description The item is visible to any other code

Any member/ derived obj The item is visible inside the declaration and to the derived type Any member/ derived obj The item is visible only within its containing asssembly Any types or memebrs The item is visible only from the type where it belongs

Any member/ derived obj The item is visible to any codes within its containing assembly and also to any code inside a derived type.

Other Modifiers New Static Virtual Abstract

Applies To

Description The method hides an inherited method with the same signature The member does not operate on specific instance of the class The member can be overriden by a derived class The method ca be defined but cannt be implemented

Function Members All members

Classes and Function Members Classes and Function Members

Override
Sealed

Function Members
Classes, methods, properties

The method overrides an inherited virtual or abstract method


such classes cannot be inherited must be used in conjunction with override.they override an inherited virtual memebr, but cannot by overridden by any memebr in any derived class the member is implemented externally in a differently language

Extern

Static methods only

Interfaces - I
Interfaces provide a contract that classes used within that interface must provide implementation of methods & properties specified by it. Interfaces can never be instantiated. It contains only the signature of its memebers. It has no constructors or fields Interface defination does not contain declaration of modifiers on its members. Interface memebrs are always, implicitly public,cannot be declared as virtual or static.Such modifiers can be used when they are implemented within the classes. Interfaces implement Inhertance i.e. a derived Interfaces can created from a base Interfaces unlike classes. Defining and Implementing Interfaces Defined with keyword interface. Ex: Banking Domain Namespace XYZComp.ProCSharp { Public interface IBankAccount { void PayIn(decimal amount); bool WithDraw(decimal amount); decimal Balance {get;} }}

Code Snippet using XYZComp.ProCSharp public class SavingAccount : IBankAccount { //.. Implementation code }

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