C Sharp Objects
C Sharp Objects
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
(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.
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.
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
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:
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.
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
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
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();
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
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;
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); } }
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() {
}
}
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.
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
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
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 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
{
}
// no 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.
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
Override
Sealed
Function Members
Classes, methods, properties
Extern
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 }