Classes and Objects
Classes and Objects
Operations
An implementation of a service that can be requested from any object of the class of which it is part
Members
The variables and functions defined inside a class are called members of the class. Types of members Data members Member functions
Methods Constructors Properties Finalizers Operators Indexer
class Customer{ public string name; public uint custId; public string address;
public void Display(){ System.Console.WriteLine(Name:+name); System.Console.WriteLine(ID:+custId); System.Console.WriteLine(Address:+address); } Accessing members from the same class } Responsibility of this class is the integrity of details of customer that it encompasses.
Question?
Can custId be 0? Which class is responsible for the integrity of the custId? What should be done so that the class makes sure that the values of the variables are meaningful?
Member Visibility
public Accessible from anywhere private Accessible from only within a class protected internal protected internal
Unmarked members are private by default
Later
Class visibility
Top-level classes (, interfaces, structures, enumerations and delegates) can only be declared as
public internal
value is not a keyword but a word that represents the implicit parameter used during property assignment in set property
Constructor
A special method used to initialize members when object is constructed. Called automatically on creation of object. Classes for which explicit constructor is not written, default constructor is automatically provided. Name of the constructor is same as the name of the class. A constructor does not have return type.
Example-Constructor
using System; class Point{ private int x,y; Point(int x,int y){ constructor this.x=x; this.y=y; } static void Main(){ Creating object by Point p1= new Point(10,20); calling the above Point p2= new Point(10,20); constructor }} Invoking new Point() generates error!
??
this
The this keyword refers to the current instance of the class. It can be used to access members from within constructors, instance methods, and instance accessors. It can be used to the current object pass an object as a parameter to a method. call(this); this is also used for constructor chaining and to declare indexers.
Constructor Chaining
public public public public } public this.x this.y } // etc } class Point{ int x ; int y ; Point():this( 0,0 ){ Point( int x, int y ){ = x ; = y ;
References
The types created for classes are called references. Unlike other basic types (like int, float etc. which are created on stack), references are created on the heap. They are implicit pointers to the object created. The space for the object allocation is not done until runtime.
p1 x=10 y=20
Type classification
Value types Basic types like int, char, float etc. struct types enum types Reference types Class types Array types Interface types Delegate types
Arrays
Arrays are references types. They are automatically of a predefined type System.Array. Creating an array: int[] n=new int[5]; Creating and initializing an array: int[] n2=new int[4]{20,10,5,13}; Or simply int[] n1={20,10,5,13};
If there is a mismatch between the declared size and the number of initializers, a compile time error is generated.
Multidimensional array
Two types of multidimensional array Rectangular array Jagged array
Rectangular Array
A multidimensional array where length of each row is fixed. Creation: int[,] matrix = new int[5,5]; Accessing array elements: matrix[0,1]=9;
Jagged Arrays
A jagged arrays are array of arrays. The arrays may be of different sizes. Creation: int[][] myarr=new int[5][]; Creating arrays in the jagged array, for(int i=0;i<myarr.Length;i++){ myarr[i]= new int[i+3]; } Accessing elements myarr[0][1]=8; Accessing the length of row 0, myarr[0].Length
BinarySearch()Searches array for a given item Clear()Sets a range of elements in the array to empty values(0 for value types,null for reference types) CopyTo()Copy elements from the source array into the destination array Length Determines the number of elements in an array(read-only property) Rank Returns the number of dimensions of the current array. Reverse()Reverses the contents of a onedimensional array. Sort()Sorts one-dimensional array of intrinsic types.
Members of System.Array
static members
Members which are accessible only at class level. Members cannot be accessed using instance. WriteLine() is a static method of System.Console class. Main is declared as static method. Static data is shared by all the instances of that class. Static member functions can access only static data members.
Static Property-Example
class Circle{ private static double PI; public static double pi{ get{return PI;} set{ PI=value;} } static void Main(){ c.pi would give error! Circle c= new Circle(); Circle.pi=3; System.Console.WriteLine(Circle.pi); }}
static constructors
Like constructors are used to initialize instance fields, static constructors are created to initialize static fields. But unlike regular constructors, static constructor
cannot have arguments. cannot have any modifier can be only single
A static constructor executes before any other constructor. It gets called just before any of the class member (static or instance or constructor) is invoked. It gets called only once.
class BankAccount{ static double rate; int acctid; double bal; public BankAccount(int acctid, double bal){ this.acctid=acctid; this.bal=bal; }
BankAccount.cs
static BankAccount(){ //assume the data is read from the database rate=0.05; }
public void calInterest(){ bal=bal+bal*rate; } public void display(){ System.Console.WriteLine("AcctID ="+acctid); System.Console.WriteLine("Bal ="+bal); } static void Main(){ BankAccount bank= new BankAccount(1,3000); bank.calInterest(); bank.display(); } }
const
Constant members can be created using const keyword. Members of const type must be initialized during compile-time. Constants are implicitly static. Therefore they are accessed using class name only. class X{ public const double PI=3.14; } Accessing outside the class: X.PI.
Question?
public const Point center= new Point(10,20); The above statement generates error. Why? Because the object is created only at runtime and const requires the value to be known at the compile time.
Lets us see.
Read-only instances
Read-only fields are assigned value only once either during compile time or runtime. They must be initialized either with the declaration or in the constructor. The keyword readonly is used for this readonly Point center= new Point(10,20); Unlike constants, read-only fields are instance members and not static members.
readonly Example
class Point{ public int x,y; public Point(int x,int y){ this.x=x; this.y=y;} } class Circle{ public readonly Point center= new Point(10,20); static void Main(){ Circle c= new Circle(); System.Console.WriteLine(c.center.x +", "+ c.center.y);} }
Question?
What is the difference between
const double PI=3.14 and readonly double PI=3.14 ?
Try to answer
What is static readonly field?
static classes
A class defined as static cannot be created using new keyword. It can contain only static members. It is useful when we need to create a kind of a utility class which just has a set of utility functions. For instance, a class that contains all the sort and search methods.
public static void exchange(int[] array) { for(int i=0;i<array.Length-1;i++) for(int j = i+1;j<array.Length;j++) if(array[i]>array[j]){ int temp=array[i]; array[i]=array[j]; array[j]=temp; } } } class Test{ static void Main(){ int[] array={1,6,4,3,7}; Common.exchange(array); for(int i=0;i<array.Length-1;i++) System.Console.WriteLine(array[i]);}}
Parameter Passing
Passing value types Pass by reference types
Prints 10
f1 stack p1 i=10
f2 stack p2
ref
class PassRef{ int i; PassRef(int i){this.i=i;} static static p= new } static i=100; } void f1(ref PassRef p){p.i=5;} void f2(ref PassRef p){ PassRef(15); void f3(ref int i){
public static void Main(){ int i=50; Must specify this while calling f3(ref i); Prints 100 System.Console.WriteLine(i); PassRef p= new PassRef(10); f1(ref p); System.Console.WriteLine(p.i); f2(ref p); System.Console.WriteLine(p.i); } }
Prints 5
Prints 15
refmod.cs
out
Similar to ref, except that the initial value of an the argument provided by the calling function is not important. In other words, the called methods will ensure that the variable defined as out will have a valid value before function exits.
using System; class OutParam{ public static void cal(int i,int j, ref int k){ k=i+j; } public static void Main(){ int i=10,j=20,k; cal(i,j,ref k); Console.WriteLine(k); } }
Compile-time Error : Use of unassigned local variable 'k'
using System; class OutParam{ public static void cal(int i,int j, ref int k){ k=i+j; } public static void Main(){ out int i=10,j=20,k; cal(i,j,ref k); Console.WriteLine(k); Prints 30 } }
OutParam.cs
params
Sending any number of argument of a particular type. There can be only one params for any method. The params argument must be the last parameter specified. The params should be a single dimensional or a jagged array.
using System; class Params{ static int sum(params int[] i){ int sum=0; for(int k=0;k<i.Length;k++) sum+=i[k]; return sum; } public static void Main(){ int s=sum(1,2,3,4); Console.WriteLine(s); Or send an array of int s=sum(11,22); Console.WriteLine(s); }}
C# Nullable Types
Default value for reference type is null. Reference values can also be explicitly assigned to null string s=null; Value types cannot be set to null int i=null; bool b=null; Not completely true because this works!!! bool? b=null; int? i=null; and string? S=Raj; gives error!!! Why would you want to assign value types as null? we will discover in the boxing section.
The ?? Operator
?? operator allows us to assign a value to a nullable type if the retrieved value is null.
Some user defined method which retrieves value(say, student id) from the database
int? studid=GetIdFromDatabase()??1;