classes in c#

Upload: shivuhc

Post on 13-Jan-2016

8 views

Category:

Documents


0 download

DESCRIPTION

C

TRANSCRIPT

  • OOPS

  • Object OrientationObject Orientation is higher level of abstraction. It has seamless transition among different phases of software development. The benefits of object-orientation are as follows:Modularity - The characteristic of a system that has been divided into smaller subsystems which interact with each otherEasier MaintenanceRe-UsabilityHigher QualityReduced CostIncreased Scalability How much a system can be expandedConcepts of OOP are1) Abstraction 2) Encapsulation 3) Class 4) Object 5) Messages6) Inheritance 7) Polymorphism

  • Abstraction It refers to the act of representing the essential features without including the background details or explanationsEncapsulationThe wrapping up of data and functions into a single unit is known as encapsulation (OR)A concept where an object totally separates its interface from its implementation is termed as encapsulationData Encapsulation is the most striking features of a classThe data is not accessible to the outside world, and only those functions which are wrapped in the class can access it.The insulation of the data from direct access by the outside world is known as data hiding or information hiding

  • ClassClass is a prototype that defines the variables and methods common to all objects of a certain kindFeaturesEncapsulates both data and operations (methods)Object is a run-time instance of a classMemory is allocated for objects and not for classesclass PhoneCustomer {public const string DayOfSendingBill = "Monday"; public int CustomerID;public string FirstName;public string LastName; } Object instance of a classSyntax to create object of the class: classname objname = new classname();PhoneCustomer objPC = new PhoneCustomer();

  • Class MembersThe data and functions within a class are known as the classs members. Members of the class can be declared with different access specifiers (or) visibility modifiersVisibility Modifiers of C# are

    ModifierDescriptionPrivateAccess is limited to the members of the same classPublicAll objects can access itProtectedAccess is limited to members of the same class or descendants InternalAccess is limited to the current assemblyProtected internalAccess is limited to the current assembly or types derived from the containing class

  • Class MembersMembers of the class can be either static or instanceStatic - Associated with the class as a wholeInstance Each instance of class has its own copy of the dataStatic members are accessible by class nameInstance members are accessible by object of classData MembersData members are those members that contain the data for the class - fields, constants, and eventsFields are any variables associated with the classPhoneCustomer Customer1 = new PhoneCustomer(); Customer1.FirstName = "Simon"; Constants can be associated with classes in the same way as variables. You declare a constant using the const keywordpublic const string DayOfSendingBill = "Monday"; Events are class members that allow an object to notify a caller whenever something noteworthy happens, such as a field or property of the class changing, or some form of user interaction occurring. The client can have code known as an event handler that reacts to the event

  • Function MembersFunction members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers and indexersMethods are functions that are associated with a particular classProperties are sets of functions that can be accessed from the client in a similar way to the public fields of the class. C# provides Get and Set to implement the propertiesConstructors are special functions that are called automatically when an object is instantiated. They must have the same name as the class to which they belong, and cannot have a return type. Constructors are useful for initializing the values of fieldsFinalizers are similar to constructors but are called when the CLR detects that an object is no longer needed. They have the same name as the class, preceded by a tilde (~)Indexers allow your objects to be indexed in the same way as an array or collection

  • Methods Declaring Methods[Access Specifiers] Return_Type MethodName([parameters]) { // Method body } E.g.: public bool IsPositive(int value) { if (value < 0) return false; return true; } Invoking the MethodThe syntax for invoking a method is exactly the same in C# as it is in C++ and Java, round brackets must always be used when invoking the method in C# E.g.: bool val = IsPositive(5);

  • Passing Parameters to MethodsArguments can in general be passed into methods by reference or by valueBy ValueThe called method gets an identical copy of the variable - which means any changes made are lost when the method exitsValue type variables hold the actual data, so a copy of the data itself will be passed into the methodIn C#, all parameters are passed by value E.g. An int, for instance, is passed by value to a method, and any changes that the method makes to the value of that int do not change the value of the original int objectvoid swap(int num1, int num2){int temp = num1; num1 = num2 ; num2 = temp;}int i = 5; int j = 6;swap(i,j);

  • By ReferenceWhen a variable is passed by reference, the called method gets the actual variable - so any changes made to the variable inside the method persist when the method exitsReference type variables only hold a reference to an object, it is this reference that will be copied, not the object itself. Hence, changes made to the underlying object will persist. E.g. An array or any other reference type, such as a class, is passed into a method, and the method uses the reference to change a value in that array, the new value is reflected in the original array objectvoid swap(ref int num1, ref int num2){int temp = num1; num1 = num2 ; num2 = temp;}int i = 5; int j = 6;swap(ref i,ref j);

  • Out ParametersIt is common for functions to be able to output more than one value from a single routine. This is accomplished using output parameters, by assigning the output values to variables that have been passed to the method by reference. The starting values of the variables that are passed by reference are unimportant. Those values will be overwritten by the function, which may never even look at any previous value.You do this with the out keyword.E.g. static void SomeFunction(out int i) { i = 100; } public static int Main() { int i; // note how i is declared but not initialized. SomeFunction(out i); Console.WriteLine(i); return 0; }

  • Method OverloadingIn order to overload methods, you simply declare the methods with the same name but different numbers or types of parameters class ResultDisplayer { void DisplayResult(string result) { // implementation } void DisplayResult(int result) { // implementation } } you should know that C# does place some minimum differences on the parameters of overloaded methodsIt is not sufficient for two methods to differ only in their return type.

  • PropertiesThe properties are used to access the private fields outside the classProperty is a method or pair of methods that are dressed to look like a field as far as any client code is concernedTo define a property in C#, you use the following syntax:public string SomeProperty { get { return "This is the property value."; } set { // do whatever needs to be done to set the property. } } The get accessor takes no parameters and must return the same type as the declared property. You should not specify any explicit parameters for the set accessor either, but the compiler assumes it takes one parameter, which is of the same type again, and which is referred to as value.

  • E.g.private string foreName; public string ForeName { get { return foreName; } set { foreName = value; } } Note the naming convention used here You take advantage of C#s case sensitivity by using the same name, Pascal-cased for the public property and camel-cased for the equivalent private field if there is one

  • Read-Only and Write-Only PropertiesIt is possible to create a read-only property by simply omitting the set accessor from the property definitionpublic string ForeName { get { return foreName; } }It is similarly possible to create a write-only property by omitting the get accessorpublic string ForeName { set { foreName = value; } }

  • ConstructorsYou declare a method that has the same name as the containing class and that does not have any return typepublic class MyClass { public MyClass() { } // rest of class definition}If you dont supply any constructor, the compiler will just make up a default one for you behind the scenes. Itll be a very basic constructor that just initializes all the member fields by zeroing them out (null reference for reference types, zero for numeric data types, and false for bool)Constructors follow the same rules for overloading as other methods

  • Static ConstructorsIt is also possible to write a static no-parameter constructor for a class. Such a constructor will be executed only once, as opposed to the constructors written so far, which are instance constructors, and are executed whenever an object of that class is created.Class MyClass { static MyClass() { // initialization code } // rest of class definition }One reason for writing a static constructor is if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

  • The .NET runtime makes no guarantees about when a static constructor will be executed, so you should not place any code in it that relies on it being executed at a particular time (for example, when an assembly is loaded). Nor is it possible to predict in what order static constructors of different classes will execute. However, what is guaranteed is that the static constructor will run at most once, and that it will be invoked before your code makes any reference to the class. In C#, the static constructor usually seems to be executed immediately before the first call to any member of the class.Notice that the static constructor does not have any access modifiers. Its never called by any other C# code, but always by the .NET runtime when the class is loaded, so any access modifier like public or private would be meaningless. For this same reason, the static constructor cannot ever take any parameters, and there can only be one static constructor for a class. It should also be obvious that a static constructor can only access static members, not instance members, of the class.

  • Note that it is possible to have a static constructor and a zero-parameter instance constructor defined in the same class. Although the parameter lists are identical, there is no conflict, because the static constructor is executed when the class is loaded, but the instance constructor is executed whenever an instance is created - so there wont be any confusion about which constructor gets executed when.Finalizers Finalizers are similar to constructors but are called when the CLR detects that an object is no longer needed. They have the same name as the class, preceded by a tilde (~)