Você está na página 1de 19

Understanding Document-Day2 Trainer Date Topics Covered Bhanu Prakash October 5th,2011 Value Types and Reference Types

OOPS Concepts

1.

Value Type vs. Reference Types

Value Type: Variables directly Contains the values.


Is allocated inline as a sequence of bytes, the location of which is based on the scope in which it is defined. Ex: Memory allocation in Stack.

All value types are derived from System.ValueType. Structure, Constant Expressions, Built-in-data types like int,bool,etc.., are value types because they are evaluated at compile time. For example in functions.., if a value is passed using passbyvalue than they are value types since the changes will not effect the original variable.

Reference Type:

It stores the address of the data.


The actual data that the address refers to is stored in an area of memory called the heap. Ex: Memory allocation in Heap Because reference types represent the address of the data rather than the data itself, assigning a reference variable to another doesnt copy the data. Instead, assigning a reference variable to

another instance creates a second copy of the reference, which refers to the same location of the heap as the original value.

Class, Interface, Delegate are reference types. string, Object are built-in reference types. For example in functions.., if a value is passed using passbyvalue than they are value types since the changes will effect the original variable.

The stack is always used to store the following two things: The reference portion of reference-typed local variables and parameters (such as the refx,refy reference) Value-typed local variables and method parameters (structs, as well as integers, bools, chars, DateTimes, etc.) The following data is stored on the heap: The content of reference-type objects. Anything structured inside a reference-type object. Common Type System (CTS): It follows the principal of Inheritance. Each type in CTS is value type and reference type.

Program Showing the Difference between the value type and reference type:

using System; class Demo { public class Test{ public void change(ref int k)//reference of variable is created { k=k+2; //Value of k is incremented by 2 } } public static void Main() { int i=3; //value type Test hi=new Test(); Console.WriteLine("Before {0} ", i);// value assigned to i is printed hi.change(ref i); //ref keyword is used so the changes made with k will effect here Console.WriteLine("After {0} ", i);//value after referring k

} } o/p: Before-3,After-5
Pass by reference can be done by two keywords in c sharp: ref and out
Ref-means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out. An argument passed by ref keyword has to be initialized. Out- means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out An argument passed by out keyword need not be initialized. "The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument."

Program showing Ref and Out Variable: class OutExample { static void SetString(int number,out string value) { if (number==1) { value="one";//Assign Out Parameter } value = "carrot";//Assign Out Parameter } static void Main(string[] args) { class RefExample { static void SetString(ref string value) { if (value == "cat") { Console.WriteLine("Is cat");//test Parameter Value } value = "dog";//Assign Parameter to new value } static void Main(string[] args) {

string value2;//value is not assigned in out parameter SetString(1,out value2); Console.WriteLine(value2) ; Console.ReadLine(); } }

string value1 = "cat";//Assign String Value SetString(ref value1); Console.WriteLine(value1) ; } }

Boxing and Unboxing: Boxing: Converting value type to reference type. UnBoxing: Converting Reference type to value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit

Class BoxingUnBoxing { Static void Main(String[] args) { Int i=20; Object o=i;//boxing Int j=(int)o;//Unboxing

} When do we use Boxing and Unboxing? To have a unified type system and allow value types to have a completely different representation of their underlying data from the way that reference types represent their underlying data. Boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be created. This can take up to 20 times longer than an assignment. When unboxing, the casting process can take four times as long as an assignment.

OOPS CONCEPTS
Procedural Programming:
Focus is on procedures All data is shared: no protection More difficult to modify. Hard to manage complexity

Object Oriented Programming


Advantages over Procedural Programming More security.

Access specifiers are used.

Data and operations are grouped together.

OOPS Concepts: Class Object Inheritance Polymorphism Abstraction Encapsulation

Class: Class is generalized representation of group of similar objects.

Class is a successor of structure, in which all the variables are by default private. Hence class provides security over data.

It is fundamental building block of code that defines data and methods that operate on data.

Object: Object is a generalized representation of a class i.e. It is nothing but an instance to a class. Once the object for a particular class is defined memory will be allocated for that class. If a particular object to a class is created then it almost certainly belongs to that class until that is destroyed. Constructors: Constructor is a special method of class whose name will be same as that of its class name. It will not have any return type even void. Used to create an object of class.

Inheritance: Process acquiring the features of base class into derived classes.

The class extending the base class will acquire base class properties along with its additional properties. It provides code usability, accessing super class members and methods by derived class.

Types of Inheritance: 1.Single Inheritance 2.Multiple Inheritance 3.Multilevel Inheritance 4.Hierarchical Inheritance 5.Hybrid Inheritance.

Types of Classes: 1. Abstract Class:

Abstract class is incomplete class which consists of complete methods and incomplete methods. Base class method should have abstract key word and derived class method should have override keyword. We cannot create object for abstract class.

using System; using System.Collections.Generic; using System.Text; namespace AbstractClass { public abstract class Absclass { public void add(int x,int y) { Console.WriteLine(x+y); } public abstract void mul(int a,int b); } class InAbsclass:Absclass { public override void mul(int a, int b) { //throw new Exception("The method or operation is not implemented."); Console.WriteLine(a*b); } public void add(int x, int y) { Console.WriteLine(x+y); } } class Program { static void Main(string[] args) { InAbsclass inabs = new InAbsclass(); inabs.mul(10,20); inabs.add(10, 20); Console.ReadLine();

} } }

2. Static Class:
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static classes can be used when there is no data or behavior in the class that depends on object identity. Static classes are sealed and therefore cannot be inherited.

3. Partial Class
It is possible to split the definition of a class over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled. To split a class definition, use the partial keyword modifier.

4. Sealed Class
A sealed class cannot be inherited. It is an error to use a sealed class as a base class. It is not permitted to use the abstract modifier with a sealed class

5. Interface
Its like an abstract class , which only consists of method declarations, will not have complete methods and variable declarations. Interface must be preceded by interface keyword. All the methods in interface are by default public and abstract. Single inheritance is allowed in classes, where as multiple inheritance allowed in interfaces.

The class which inherits or implements interface use : operator. If two interface has same method, than which interface method will invoke, can be done by using the interfacename.methodname in the implementation.

Program on Interface:
using System; using System.Collections.Generic; using System.Text; namespace InterfaceExample { interface FirstInterface { int add(int FirstVal, int SecVal); int mul(int a, int b); } interface SecondInterface { int add(int x, int y); int sub(int p, int q); } class ImplementInterface:FirstInterface,SecondInterface { #region FirstInterface Members { int FirstInterface.add(int FirstVal, int SecVal)

//throw new Exception("The method or operation is not implemented."); return (FirstVal+SecVal); } int FirstInterface.mul(int a, int b) { //throw new Exception("The method or operation is not implemented."); return(a*b); } #endregion

#region SecondInterface Members

int SecondInterface.add(int p, int q) //throw new Exception("The method or operation is not implemented."); return (p + q); } int SecondInterface.sub(int x,int y) { } return(x-y); {

#endregion } class Program { static void Main(string[] args) { ImplementInterface ImpInt=new ImplementInterface() ; FirstInterface FI=new ImplementInterface(); SecondInterface Si=new ImplementInterface(); Console.WriteLine( FI.add(10,20)); Console.WriteLine(FI.mul(10,20)); Console.WriteLine(Si.add(10,200)); Console.ReadLine(); } } }

Encapsulation
Encapsulation is an object-oriented principle of hiding the internal state and behavior of an object, making your code more maintainable. In C#, you can manage encapsulation with access modifiers.

Access Modifier

Description (who can access)

private

Only members within the same type. (default for type members)

protected

Only derived types or members of the same type.

internal

Only code within the same assembly. Can also be code external to object as long as it is in the same assembly. (default for types)

protected internal

Either code from derived type or code in the same assembly. Combdfination of protected OR internal.

public

Any code. No inheritance, external type, or external assembly restrictions.

Auto Implemented Properties:


When a property is specified as an automatically implemented property, a hidden backing field is automatically available for the property, and the accessors are implemented to read from and write to that backig field. The following ex: Public class point{ Public int x{get ,set}//automatically implemented Public int y{get ,set}//automatically implemented } Is equivalent to following declaration Public class point{

Private int x;private int y; Public int X{get{return x;}set{x=value;}} Public int X{get{return x;}set{x=value;}}}

POLYMORPHISM:
Its a process in which single object undergoes into many forms. Or object having many forms. Two types of polymorphism: 1.Compile time : Also known as early binding static polymorphism. Ex:function overloading, operator overloading. 2.Run time : Also known as late binding dynamic polymorphism. Ex:function overriding, operator overloading.

Function Overloading
Function with same name and with different signatures. EX Class sample{ Public int sum(int x,int y) { Return(x+y) } Public double sum(double x,double y) { Return(x+y) }

class prgm { Public static void main() { Sample s =new sample(); Double result=s.sum(20,22); Console.WriteLine(result is+result); } }

LIMITATIONS OF FUNCTION OVERLOADING


Return type is not included in the signature. If the paramaters are same and retun type is different it gives compile time error.

FUNCTION OVERRIDING
Function with same name and same signature. In function overriding will use virtual keyword in base class and override keyword in derived class. using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace Funcoverriding

{ public class swap1 { public virtual void swap(int a, int b) { int c; Console.WriteLine("before swap using base method a:" +a + "b:" +b); c=a; a=b; b=c; Console.WriteLine("after swap using base method a:" +a + "b:" +b); } } class swap2:swap1 { public override void swap(int a, int b) { Console.WriteLine("before swap using derived method a:" +a + "b:" +b); a=a+b; b=a-b; a=a-b; Console.WriteLine("after swap using derived method a:" +a + "b:" +b);

} }

class Program { static void Main(string[] args) { swap1 s=new swap1(); s.swap(15,25);// to call method of base class // swap1 s1; // s1=new swap2(); // s1.swap(10,20);//to call method of derived class Console.ReadLine(); } } }

Você também pode gostar