Professional Documents
Culture Documents
Before the existance of dot net frame work , there were languages such
as vb , vc++ , asp etc were being executed in their respective platforms.
It supports 32 languages.
What is .net :
It is a platform neutral framework
.net is a layer between the operating system and programming
lanaguage
It supports many programming languages , including vb.net , c# etc
.net provides a common set of libraries , which can be accessed
from any .net based programming language. There will not be
separate set of classes and libraries for each language.
.net is a framework.
Note:
Runtime layer is refered to as clr.
The primary role of the clr is to locate , load and manage .net types.
The clr also takes care of number of low-level details such as memory
management and performing security checks.
Clr manages
Garbaze collection
Threading
Clr is one which reads the source code and converts into appropriate
il ( intermediate language)
Another building block of .net platform is the common type system (cts).
The cts specification fully describes all possible data types and
programming constructs supported by the runtime.
It specifies how these entities can interact with each other and details
how they are represented in the .net metadata format.
It is one which identifies the data types.
Base class library defines types that facilitate database access ,xml
manipulation ,programming security and construction of web enabled front
ends.
.net solution:
Core features of .net
Full interoperability with existing code.
Existing com binaries can mingle with newer .net binaries and
vice versa.
Platform invocation services allows user to invoke c-based
libraries from .net code.
Complete and total language integration.
.net supports cross language inheritance , cross language
exception handling and cross language debugging.
Benefit of cil :
The one benefit is language integration.
Meta data :
Meta data could describe if a component required a database transaction
or if the component should participate in object pooling.
Il and
Meta data
(*.dll or *.exe)
Cobol .net
Source code -----------------> cobol .net compiler------------>
Manged c++
Source code ----------------> managed c++ compiler---------->
Note:
Cil like java byte code.
Meta data describes the characterstics of every type living with in the
binary.
Ex : it specifies the base class of the user defined class , which interfaces
are implemented.
.net meta data is always present and is automatically generated by a given
.net aware compiler.
In addition to cil and meta data , assemeblies them selves are also
described using meta data which is called as "manifest"
When building multi file assembly one of these module termed the primary
module must contain the assembly manifest(cil instructions and meta
data for various types).
The other module contains cil , type meta data ,module level manifest.
Why multi file assemblies are required :
When the assemblies are partitioned to different modules. It provides more
flexible deployement option.
Ex: remote assembly to be downloaded , the runtime will down load only
required modules.
If all the types are placed in single file assembly. Then while down loading
large volume or chunk of data is down loaded. It is a waste of time
System.byte byte
System.sbyte sbyte
System.int16 short
System.int32 int
System.int64 long
System.uint16 ushort
System.uint32 uint
System.uint64 ulong
System.single float
System.double double
System.object object
System.char char
System.string string
System.decimal decimal
System.boolean bool
System :
It is the core name space for programming.
It includes base types like string , datetime, boolean
System.io :
Allows the user to read or write to different streams.
System.data :
This represents ado.net architecture.
System.drawing :
Provides access to gdi graphics functionality.
System.threading
It facilitates multi threading.
C sharp can also be called as ( c#)
Variable :
It is a memory location which is used to store or hold the value. The value
entered is not fixed. It varies.
Namespace consoleapplication18
{
Class program
{
Static void main(string[] args)
{
Console.writeline("this is testing");
}
}
}
Using system :
It provides the compiler with knowledge of the types in the system name
space.
Modifiers : it allows the user to control access to the class and to restrict
the ability of the class to be instantiated.
These class modifers are public, protected, internal , private, abstract ,
sealed ,new.
Object:
It is an instance of a class in memory. New keyword is to create an object.
The new keyword is to aquire sufficient memory from the managed heap
for the specified object.
Class-level scope:
Variables that are defined at class -level become available to any non static
method with in the class.
Private :
These members are available only to that class.
Protected :
These members are available to its own class and to the derived class.
Public:
Internal : the members can be reached from with in the same project only.
Protected internal:
Same as internal . Except that also classes classes which inherits from this
class can reach its members even from another project.
Nested scope:
Variables declared with in the nested scope are not available to those
Outside of their code block.
Ex:
If(condition)
{
String x="abc";
}
X is not available outside if.
Console class:
This class provides a c# application with access to standard input, standard
output, standard error.
Structure:
Structs derive from value system.valuetype. Where as classes derive from
system.object
Structs cannot derive from any other class / struct.
Nor they can be derived from.
C# does not allow structs to have a default parameterless constructor.
(because it is value type).
Struct can implement any number of interfaces.
Even though the "new" keyword is used , struct gets allocated on the
stack.
Interface abc
{
Void get();
}
Struct xyz : abc
{
Public void get()
{
Console.writeline("interface method defined");
}
- }
Class program
{
Static void main(string[] args)
{
Xyz obj = new xyz();
Obj.get();
}
}
Constructor :
It is a special method. It is used when instantiating a class.
It is called automatically as soon as the object or instance is created. It is
used to initialize the data memers of the class.
Note: constructor has the same name as that of the class name.
Constructor does not have return type.
Class sample
{
Public sample() // constructor
{
}
}
Types of constructor:
Default constructor
Parameterized constructor
Constructor overloading:
A class having several constructors , but with different parameters.
Namespace consoleapplication25
{
Class program
{
Static void main(string[] args)
{
Console.writeline("this is simple program");
}
}
}
The first three lines are name spaces.
Console is a class. Writeline() is a method.
Console class is available in system name space.
The class is declared with the keyword "class" and then name of the
class.
And in the braces , definition and methods of the class are written.
The varible declared with in the loop . Then its scope will be limited to that
loop.
If the variable is declared with in the code block like method then its scope
will be limited to that class.
If the class variable then its scope will be limited to that class.
Initialization ensures that , variable have valid values when expressions are
evaluated.
Value types and reference types :
Value types directly contain their data and instances of value types are
either allocated on the stack or allocated inline in a structure.
Reference types:
Reference types store a reference to the values memory address and
are allocated on the heap.
Namespace consoleapplication1
{
Class temp
{
Public int x;
Public string s;
Public bool b;
Public object obj;
}
Class program
{
Static void main(string[] args)
{
Temp t = new temp();
Console.writeline(t.x); // 0
Console.writeline(t.s); //null
Console.writeline(t.b);//false
Console.writeline(t.obj);//null
}
}
}
Member variable initialization :
Using system;
Using system.collections.generic;
Using system.text;
Namespace consoleapplication1
{
Class temp
{
Public int x;
Public string y;
Public temp()
{
X = 100;
}
Public temp(string s)
{
X = 200;
Y = s;
}
Public void put()
{
Console.writeline(x);
}
Public void set()
{
Console.writeline(y);
}
}
Class program
{
Static void main(string[] args)
{
Temp t = new temp();
Temp t1 = new temp("abc");
T.put();
T1.set();
}
}
}
Constant data:
The variable with a fixed and unalterable value.
The keyword const is used.
Any attempt to to alter it results in a compilation error.
Constant variable is known at a compile time.
Constant member cannot be assigned to an object reference.
(because whole value is computed at runtime)
Class consdata
{
Public const string x = "csharp";
Public const double y = 3.14;
Public const bool z = true;
}
Class program
{
Static void main(string[] args)
{
Console.writeline(consdata.x);//referencing const data using
external type
Console.writeline(consdata.y);// prefixing is required
Console.writeline(consdata.z);
Consdata.x = "xyz"; //wrong
Consdata.y = 24.67; //wrong
Console.writeline(consdata.x);
Console.writeline(consdata.y);
Const int x = 100; //correct ,
current member,no prefixing
Console.writeline(x); //correct
}
}
Note:
Constant fields are implicitly "static"
Object cannot access constant members ,private and protected members .
Class cannot access private members
Private const string x="abc"; // wrong
Static methods:
Using system;
Using system.collections.generic;
Using system.text;
Namespace consoleapplication3
{
Class sample
{
Public static void display()
{
Console.writeline("static method invoked");
}
}
Class program
{
Static void main(string[] args)
{
Sample.display();
}
}
}
Class program
{
Static void main(string[] args)
{
Savingsaccount s1 = new savingsaccount(1000);
Savingsaccount s2 = new savingsaccount(2000);
}
}
Class program
{
Static void main(string[] args)
{
Static class:
}
}
Class savingsaccount
{
Public double curbalance;
Public static double curintrate;
Class program
{
Static void main(string[] args)
{
Static constructor:
Any constructor which is preceded with the keyword "static" is static
constructor.
}
Public sample(int m)
{
X = m;
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Sample s = new sample(100);
}
}
Class sample
{
Int x;
Static sample() // static constructor
{
Console.writeline("static constructor");
}
Public sample()
{
// x = m;
Console.writeline("khkhh");
}
}
Class program
{
Static void main(string[] args)
{
Sample s = new sample();
}
}
Class savingsaccount
{
Public double curbalance;
Public static double curintrate;
Static savingsaccount() //static constructor
{
Curintrate = .05;
}
Public savingsaccount(double balance)
{
Curbalance = balance;
Console.writeline(curbalance);
}
Public static void setintrate(double intrate)
{
Curintrate = intrate;
}
Public static double getintrate()
{
Return curintrate;
}
// public void setintrateobj(double intrate)
// {
// curintrate = intrate;
// }
Public double getintrateobj()
{
Return curintrate;
}
}
Class program
{
Static void main(string[] args)
{
Note:
Static data member can be accessed inside the static and non static
functions.
Static functions (static constructor and static functions )
Can access only static data members. It does not access non static
members.
Method parameter modifiers:
None
Out
Params
Ref
None:
If the parameter is not marked with a parameter modifier, it is assumed to
be passed by value, meaning the called method receives a copy of the
original data.
Out:
Output parameters are assigned by the method being called .if the called
method fails to assign output parameters,you are issued a compile error.
Params:
This parameter modifier allows the user to send in a variable number of
identically typed arguments as a single logical parameter.
Member can have only one single params modifier and it must be final
parameter of the method.
Ref:
The value is initially assigned by the caller and may be optionally
reassigned by the called method.
Class sample
{
Public static void fillvalue(out int a, out string b, out bool c)
{
A = 100;
B = "harsha";
C = true;
Console.writeline(a + " " + b + " " + c);
}
}
Class program
{
Static void main(string[] args)
{
Int x;
String y;
Bool z;
Sample.fillvalue(out x, out y, out z);
Console.writeline(x + " " + y + " " + z);
}
}
Class program
{
Public static void fillvalue(out int a,out string b,out bool c)
{
A=100;
B="xxx";
C=true;
Console .writeline (a+" "+b+" "+c);
}
Static void main(string[] args)
{
Int x;
String y;
Bool z;
Fillvalue (out x,out y,out z);
}
}
Class program
{
Public static void swapstring(ref string s1, ref string s2)
{
String tempstr = s1;
S1 = s2;
S2 = tempstr;
}
Static void main(string[] args)
{
String s = "abc";
String s1 = "harsha";
Console.writeline("{0},{1}", s, s1);
Swapstring(ref s, ref s1);
Console.writeline("{0},{1}", s, s1);
}
}
Class program
{
Public static void swap(ref int x, ref int y)
{
Int temp;
Temp = x;
X = y;
Y = temp;
}
Class program
{
Static void main(string[] args)
{
String[] books ={ "csharp", "java", "dotnet" };
Foreach (string s in books)
{
Console.writeline(s);
}
}
}
Built in type :
Ex: int , float
Note:
All value types contain data and they cannot be null.
Note:
All of the base data types are defined in the system name space.
All types are derived from system.object
Int x =100;
Enumeration types:
Enumerations are use full when a variable can only have a specific set of
values.
Ex:
Enum color {red ,green,blue}
Structures:
Structure is allocated on the stack.
Value types can be removed from the stack once they are out of the
defining scope.
Note:
All structures are derived from system.valuetype
}
}
Struct mypoint
{
Public int x, y;
}
Class program
{
Static void main(string[] args)
{
Mypoint p1 = new mypoint();
P1.x = 100;
P1.y = 200;
Mypoint p2 = p1;
Console.writeline(p1.x + " " + p1.y + " " + p2.x + " " + p2.y);
P2.x = 0;
P2.y = 30;
Console.writeline(p2.x + " " + p2.y+" "+p1.x + " "+p1.y);
}
}
}
}
Keywords:
These are reserved identifiers.
Abstract , base, bool ,if , finally
Reference types:
Reference type variables contain references to their data.
The data for reference types variables is stored in object.
It is possible for two reference type variables to reference the same object.
Value types containing reference types:
Class shapeinfo
{
Public string x;
Public shapeinfo(string s)
{
X = s;
}
Struct rectangle
{
Public shapeinfo rectinfo; //reference type in value type
Public int top, left, bottom, right;
Public rectangle(string z)
{
Rectinfo = new shapeinfo(z);
Top = left = 10;
Bottom = right = 100;
}
}
Class program
{
Static void main(string[] args)
{
Rectangle r1 = new rectangle("this is rectangle shape");
Rectangle r2;
R2 = r1;
R2.bottom = 4000;
R2.rectinfo.x = "this is new info";
Console.writeline(r1.rectinfo.x);
Console.writeline(r2.rectinfo.x);
Console.writeline(r1.bottom);
Console.writeline(r2.bottom);
}
}
}
Namespace consoleapplication14
{
Class person
{
Public string fullname;
Public int age;
Public person(string n, int a)
{
Fullname = n;
Age = a;
}
// public person()
// {
// }
Public void printinfo()
{
Console.writeline(fullname + " " + age);
}
}
Class program
{
Public static void display(person p)
{
P.age = 100;
P = new person("abc", 120);
P.printinfo();
}
Static void main(string[] args)
{
Person p1 = new person("harsha", 22);
P1.printinfo();
Display(p1); // passing by value
P1.printinfo();
}
}
}
Class person
{
Public string fullname;
Public int age;
Public person(string n, int a)
{
Fullname = n;
Age = a;
}
// public person()
// {
// }
Public void printinfo()
{
Console.writeline(fullname + " " + age);
}
}
Class program
{
Public static void display (ref person p)
{
P.age=55;
P=new person("zzz",999);
}
Static void main(string[] args)
{
Person p1 =new person("xxx",23);
P1.printinfo ();
Display (ref p1); // passing by reference
P1.printinfo ();
}
}
allocated instance
Must derive from system.valuetype can derive from other
type
excect system.valuetype
Variables are passed by value variables are passed
by reference
When the value is boxed ,the clr allocates a new object on the heap and
copies the value types value into the instance.
In turn the reference is obtained to the newly allocated object.
}
}
C# compiler automatically boxes variables at appropriate situations.
Ex: passing a value type into a method requiring an object parameter.
Class program
{
Static void main(string[] args)
{
Int x = 100;
Display(x);
}
Static void display(object ob)
{
Console.writeline(ob);
}
}
Note:
Automatic boxing also occurs with the types of .net class library.
Ex:
System.collections name space defines a class type named
"arraylist" .
Class program
{
Static void main(string[] args)
{
Arraylist a = new arraylist();
A.add(100);
A.add(200);
A.add(300);
Foreach (int x in a)
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Arraylist a = new arraylist();
A.add(100);
A.add(200);
A.add(300);
//foreach (int x in a)
// console.writeline(x);
Int y = a.count;
For (int i = 0; i < y; i++)
{
Int z = (int)a[i]; // unboxing
Console.writeline(z);
}
}
Unboxing custom value types:
A boxing operation also occurs while passing custom structures or
enumerations into a method prototyped "system.object"
Struct mypoint
{
Public int x, y;
}
Class program
{
Static void main(string[] args)
{
Mypoint m;
M.x=100;
M.y = 200;
Display(m);
}
Static void display(object obj)
{
If (obj is mypoint)
{
Mypoint my = (mypoint)obj; // unboxing
Console.writeline(my.x + " " + my.y);
}
}
}
Enum emptype
{
Manager = 10,
President = 1,
Contractor = 5
}
Class program
{
Static void display(emptype emp)
{
Switch (emp)
{
Case emptype.manager:
Console.writeline("you are manager");
Break;
Case emptype .president:
Console.writeline("you are president");
Break;
Case emptype.contractor:
Console.writeline("you are contractor");
Break;
Default:
Break;
}
}
Static void main(string[] args)
{
Emptype e;
E = emptype.president ;
Display(e);
}
}
Enum emptype
{
Manager = 10,
President = 1,
Contractor = 5
}
Class program
{
Static void main(string[] args)
{
Array obj = enum.getvalues(typeof(emptype));
Console.writeline("this enum has {0} members", obj.length);
Foreach(emptype e in obj)
{
Console.writeline("string name {0}",e.tostring ());
Console.writeline (enum .format (typeof (emptype),e,"d"));
}
}
Overriding system.object.tostring()
Class person
{
Private string firstname;
Private string lastname;
Public person(string fname,string lname)
{
Firstname = fname;
Lastname = lname;
}
Public override string tostring()
{
{
Stringbuilder sb = new stringbuilder();
Sb.appendformat("firstname={0}", this.firstname);
Sb.appendformat("lastname={0}", this.lastname);
Return sb.tostring ();
}
}
Class program
{
Static void main(string[] args)
{
String x;
Person p1 = new person("harsha","kumar");
X= p1.tostring();
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
String s = "dotnet class ";
Console.writeline(s.length);
Console.writeline(s.toupper());
Console.writeline(s.tolower());
Console.writeline(s.substring(3));
Console.writeline(s.remove(5));
Console.writeline (s.insert (2,"dotnet"));
Console.writeline(s.indexof('a'));
Console.writeline(s.replace("dotnet", "java"));
}
}
Escape characters :
\n ----------> new line
\r ------------> carriage return
\t------------> tab space
\\---------->insert back slash
\' -------->insert a quote
Array types:
}
}
Multidimensional arrays:
Class program
{
Static void main(string[] args)
{
Int [,] x =new int[10,10];
Int m, n;
Console.writeline("enter the order of the matrix");
M = int.parse(console.readline());
N = int.parse(console.readline());
Console.writeline("enter the values for the matrix");
For (int i = 0; i < m; i++)
For (int j = 0; j < n; j++)
X[i,j] = int.parse(console.readline());
Console.writeline("the values of the matrix is ");
For (int i = 0; i < m; i++)
{
For (int j = 0; j < n; j++)
Console.write(x[i,j]+" ");
Console.writeline(" ");
}
}
}
Jagged array :
It is an array of arrays.
Jagged array is also a type of multidimensional array. Jagged arrays
contain some number of inner arrays. Each of which may have unique
upper limit.
Class program
{
Static void main(string[] args)
{
Int[][] x = new int[5][];
For (int i = 0; i < x.length; i++)
X[i] = new int[i + 7];
For (int i = 0; i < 5; i++)
{
Console.write(x[i].length+"\t");
For (int j = 0; j < x[i].length; j++)
Console.write(x[i][j] + " ");
Console.writeline();
}
}
}
Class program
{
Static void main(string[] args)
{
}
Nullable types:
To define a nullable type , the question mark symbol is suffixed to
underlying the data type.
It is applied to value types or array of value types.
Nullable types represent all the types plus the value null.
Class program
{
Static void main(string[] args)
{
Int ?Nullableint =null ;
Double? Nullabledouble =null;
Bool? Nullable = null;
Char? Nullablechar = null;
Int?[] arrayofnullableints = new int?[10];
Console.writeline(nullableint);
Console.writeline(nullabledouble);
Console.writeline(nullable);
Console.writeline(arrayofnullableints);
Console.writeline(nullablechar);
Nullableint = 200;
Console.writeline(nullableint);
Bool? X = null;
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Int? Nullableint = 100;
Double? Nullabledouble = 23.44;
Bool? Nullable = null;
Char? Nullablechar = 'a';
Int?[] arrayofnullableints = new int?[10];
Console.writeline(nullableint);
Console.writeline(nullabledouble);
Console.writeline(nullable);
Console.writeline(arrayofnullableints);
Console.writeline(nullablechar);
Nullableint = 200;
Console.writeline(nullableint);
}
}
Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue ;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}
Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase();
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase();
Console.writeline(z);
}
}
Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue =true;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}
Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase();
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase();
Console.writeline(z);
If (z == null)
Console.writeline("not defined");
Else
Console.writeline(z);
}
}
?? Operator:
This operator allows the user to assign a value to a nullable type if the
retrieved value is null.
Class databasereader
{
Public int? Numericvalue;
Public bool? Boolvalue;
Public int? Getintfromdatabase()
{
Return numericvalue;
}
Public bool? Getboolfromdatabase()
{
Return boolvalue;
}
}
Class program
{
Static void main(string[] args)
{
Databasereader obj = new databasereader();
Int? X = obj.getintfromdatabase()??125;
Console.writeline(x);
Bool? Z = obj.getboolfromdatabase()??False ;
Console.writeline(z);
If (z == null)
Console.writeline("not defined");
Else
Console.writeline(z);
}
}
Namespace:
It is a collection of classes.
Using:
It is the directive used to use the namespace.
Using system;
Class employee
{
Private string fullname;
Private int empid;
Private float currpay;
Public employee()
{
}
Public employee(string fullname, int empid, float currpay)
{
This.fullname = fullname;
This.empid = empid;
This.currpay = currpay;
}
Public void givebonus(float amount)
{
Currpay += amount; //currpay =currpay +amount ;
}
Public void display()
{
Console.writeline(fullname);
Console.writeline(currpay);
Console.writeline(empid);
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee("harsha", 100, 25000);
Employee e2 = new employee("kumar", 200, 1200);
E1.givebonus(500);
E2.givebonus(600);
E1.display();
E2.display();
}
}
Pillars of oops:
Encapsulation
Inheritance
Polymorphism
Encapsulation:
It hides the unncessary implementation details from the object user.
It also specifies the data protection.
Inheritance:
Drawing the properties from the existing to the newly defined class.
It allows the user to extend the behaviours of base class to derived class.
This specifies , a class can define a member variable of another class and
expose the functionalities to outside world.
Ex:
Public class radio
{
Public void power(bool turnon)
{
Console.writeline(turnon);
}
}
Public class car
{
Private radio r = new radio();
Public void turnonradio(bool onoff)
{
R.power(onoff);
}
}
Class program
{
Static void main(string[] args)
{
Car viper = new car();
Viper.turnonradio(true);
}
}
Polymorphism:
Class shapes
{
Public void draw()
{
Console.writeline("specifies shapes");
}
}
Class circle :shapes
{
Public void draw()
{
Console.writeline("circle class method");
}
}
Class hexagon :shapes
{
Public void draw()
{
Console.writeline("hexagon class method");
}
}
Class program
{
Static void main(string[] args)
{
Shapes[] obj = new shapes[3];
Obj[0] = new circle();
Obj[1] = new hexagon();
Obj[2] = new circle();
Foreach (shapes s in obj)
S.draw();
}
}
Class shapes
{
Public virtual void draw()
{
Console.writeline("specifies shapes");
}
}
Class circle :shapes
{
Public override void draw()
{
Console.writeline("circle class method");
}
}
Class hexagon :shapes
{
Public override void draw()
{
Console.writeline("hexagon class method");
}
}
Class program
{
Static void main(string[] args)
{
Shapes[] obj = new shapes[3];
Obj[0] = new circle();
Obj[1] = new hexagon();
Obj[2] = new circle();
Foreach (shapes s in obj)
S.draw();
}
}
Class employee
{
Private string fullname;
Public string getfullname()
{
Return fullname;
}
Public void setfullname(string s)
{
Fullname = s;
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.setfullname("harsha");
String x =e1.getfullname();
Console.writeline(x);
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.id =100;
E1.fullname ="abc";
E1.pay =17000;
Using constructor:
Class employee
{
Private int empid;
Private float currpay;
Private string fullname;
Private int age;
Public employee(int id, string name, int pay)
{
Empid = id;
Fullname = name;
Currpay = pay;
}
Public int id
{
Get
{
Return empid;
}
}
Public string name
{
Get
{
Return fullname;
}
}
Public int age
{
Get
{
Return age;
}
Set
{
Age = value;
}
}
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee(100, "harsha", 17000);
E1.age = 24;
Console.writeline(e1.id + " " + e1.name + " " + e1.pay+"
"+e1.age );
}
}
Static properties:
Class employee
{
Private static string companyname;
Public static string company
{
Get
{
Return companyname;
}
Set
{
Companyname = value;
}
}
}
Class program
{
Static void main(string[] args)
{
Employee.company ="abc";
Console.writeline(employee.company);
}
}
Note: when the public field is static , then the data member should also be
static
Class employee
{
Private static string companyname;
Public string company
{
Get
{
Return companyname;
}
Set
{
Companyname = value;
}
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new employee();
E1.company = "xxx";
Console.writeline(e1.company);
}
}
Get
{
Return name ;
}
}
Public int empno
{
Set
{
Empno =value ;
}
Get
{
Return empno;
}
}
Class salesperson : employee
{
Public int numbofsales;
Public int nsales
{
Set
{
Numbofsales =value ;
}
Get
{
Return numbofsales ;
}
}
Class program
{
Static void main(string[] args)
{
Salesperson s = new salesperson();
S.name = "harsha";
S.empno = 100;
S.numbofsales = 25;
Console.writeline(s.empno + " " + s.name + s.numbofsales);
}
}
}
Class resume
{
Protected int age;
Protected string name;
Public resume(int a, string s)
{
Age = a;
Name = s;
}
}
Class resume1 : resume
{
Protected string qual;
Protected int exp;
Public resume1(int x, string y, string z, int p)
}
Class program
{
Static void main(string[] args)
{
Resume1 r = new resume1(24, "harsha", "be", 2);
R.display();
}
}
Preventing inheritance: (sealed classes)
The class which cannot be further sub classed.
It can be done by using sealed keyword.
Class a
{
Public void check()
{
Console.writeline("base class function");
}
}
Sealed class b : a
{
Public void check()
{
Console.writeline("b class fun");
}
}
Class program
{
Static void main(string[] args)
{
Second s = new second();
S.accept();
}
}
Class first
{
Public int display()
{
Return 100;
}
}
Class second
{
Protected first f = new first();
Public int accept()
{
Return f.display();
}
}
Class program
{
Static void main(string[] args)
{
Second s = new second();
Int m = s.accept();
Console.writeline(m);
}
}
Class program
{
Static void main(string[] args)
{
Employee obj1 =new employee ();
Double d =obj1.verify.compute();
Double d1=obj1.getcost();
Console.writeline(d);
Console.writeline(d1);
}
}
Nested type definition:
The types such as enum , class,interface, struct or delegate) can be
defined with in the scope of the class or structure.
Public class outer
{
Public class inner
{
Public void display()
{
Console.writeline("inner class method");
}
}
Class program
{
Static void main(string[] args)
{
Class program
{
Static void main(string[] args)
{
Outer.inner.enumdays e = outer.inner.enumdays.wednesday;
Console.writeline(e);
Obj.display ();
}
}
Third pillar of oops concept:
Polymorphism:
The base class wishes to define a emthod that may be overridden by a sub
class.
Public class employee
{
Float curpay;
Public virtual void givebonus(float amount)
{
Curpay = amount;
Console.writeline(curpay);
}
}
Public class salesperson : employee
{
Public override void givebonus(float amount)
{
Base .givebonus (amount );
Console.writeline("iam in salesperson");
}
}
Class program
{
Static void main(string[] args)
{
Manager obj1 = new manager();
Obj1.givebonus(1000);
Salesperson obj2 = new salesperson();
Obj2.givebonus(2000);
}
}
Abstract class:
It is one which contains abstract method.
For the abstract class object cannot be created.
Abstract method has to be overridden in derived class.
}
}
Abstract class can also contain only declared method( abstract method
only)
}
}
}
Class circle : shape
{
Class program
{
Static void main(string[] args)
{
Hexagon hex =new hexagon ();
Hex.draw ();
Circle cir =new circle ();
Cir.draw ();
}
}
Member hiding:
It is opposite of method overriding.
It is used to hide the parent version.
(derived types implementation hides the parents version).
Implicit casting:
Storing the derived type with in a base class reference.
Ex:
Employee e = new manager();
Class employee
{
Protected int empno;
Public void getinfo()
{
Empno = 100;
}
}
Class manager : employee
{
Public void putinfo()
{
Console.writeline(empno);
}
}
Class sales:employee
{
Protected string name;
Public void getname()
{
Name = "abc";
}
}
Class x
{
Public static void output (employee e)
{
If (e is manager)
{
E.getinfo();
Console.writeline(e);
}
If (e is sales)
{
E.getinfo();
Console.writeline(e);
}
}
}
Class program
{
Static void main(string[] args)
{
Employee e1 = new manager();
Employee e2 = new sales();
X.output(e1);
}
}
Numerical cast :
Class program
{
Static void main(string[] args)
{
Int x = 100;
Byte b = (byte) x; // explict cast
Console.writeline(b);
Byte b1 = 30;
Int y = b1; //implicit cast
Console.writeline(y);
}
}
Partial type:
Partial modifier allow c# type acro multiple *.c file
Exception handling:
Bugs:
Putting an error on the part of the programmer.
Ex: fail to delete allocated memory. Resulting in memory leak. This is a
bug.
Error:
Errors are caused by the individual running the application.
Exception :
Exceptions are typically regarded as runtime anomolies.
Ex: dividing a number by zero.
Attempting to connecting to data base which is no longer exists.
The .net base class library defines numerous exceptions such as
Formatexception
Indexoutofrangeexception
Filenotfoundexception
The keywords used to throw and handle exceptions are try , catch, finally,
throw
All the user and system defined exceptions ultimately derive from
system.exception
Int a = int.parse(console.readline());
Int c = a / b;
}
}
}
Finally block :
Finally block is to ensure that set of code statements will always execute.
Whether the exception is thrown or not.
Using system;
Using system.collections.generic;
Using system.text;
Namespace example4
{
Class program
{
Static void main(string[] args)
{
Try
{
Console.write("a = ");
Int a = int.parse(console.readline());
Console.write("b = ");
Int b = int.parse(console.readline());
Int c = a / b;
Console.writeline(" {0} / {1} = {2}", a, b, c);
Finally
{
Console.writeline("executing finally block");
}
}
}
}
Catch(exception e)
{
Throw e;
}
Inner exception :
Encountering an exception while processing another exception.
Ex:
Catch(sampleexception e)
{
Try
{
}
Catch(exception error)
{
Finalization type :
A class could contain finalizer, which executes when the object is
destroyed.
Dispose :
Instead of declaring a finalizer, the dispose method can be used.
If the obejct is cleaned up by using dispose method or close method , then
it indicates to the runtime that the object is no longer needed finalization
by calling gc.suppressfinalize() .
}
~sample()
{
Dispose();
}
}
Class program
{
Static void main(string[] args)
{
Sample s = new sample();
Using (s )
{
Console.writeline("before leaving using statement");
}
Console.writeline("after leaving using statement");
}
Weak references:
Weak references are means of performance enhancement. Used to reduce
the pressure place on the managed heap by large objects.
The managed heap contains two internal data structures to manage weak
references.
Short weak reference table and long weak reference table.
Note: all the reference types will exist in one of these 3 generations.
They will firstly be allocated to gen 0, then moved to gen1 and gen 2
depending on their life time.
Class program
{
Static void main(string[] args)
{
Console.writeline("estimated bytes on heap {0}",
gc.gettotalmemory(false));
Console.writeline("{0} the object generations ",
gc.maxgeneration+1);
}
}
Interfaces :
Interface is nothing but a named collection of abstract members.
Class a : abc
{
Public void get()
{
}
}
Note:
Interface must be listed after colon operator.
Syntax:
Class classname : interfacename
Implementing interface :
Interface xyz
{
Void get1();
}
Class p1 : xyz
{
Public void get1()
{
Console.writeline("interface method");
}
}
Class program
{
Static void main(string[] args)
{
P1 obj = new p1();
Obj.get1();
}
}
Drawing the properties from only one class and implementing any number
of interfaces.
Class p1
{
Public void get1()
{
Console.writeline("this is class method");
}
}
Interface xyz
{
Void get2();
}
Class p2 : p1,xyz
{
Public void get2()
{
Console.writeline("interface method");
}
}
Class program
{
Static void main(string[] args)
{
P2 obj = new p2();
Obj.get1();
Obj.get2();
}
}
}
}
Class program
{
Static void main(string[] args)
{
X x1 = new abc();
X1.get();
X1 = new pqr();
X1.get();
}
}
}
Class a : abc
{
Public int x
{
Get
{
Return 100;
}
}
}
Class program
{
Static void main(string[] args)
{
Abc obj;
A obj1 =new a();
Obj =(abc)obj1;
// obj.x = 200;
Console.writeline (obj.x);
}
}
Public class fc
{
Protected string data;
Public string data
{
Get
{
Return this.data;
}
Set
{
This.data = value;
}
}
}
Interface xyz
{
Bool validate();
}
Class mc : fc,xyz
{
Public mc()
{
Data ="checking";
}
Public bool validate()
{
Console.writeline (data);
Return true ;
}
}
Class program
{
Static void main(string[] args)
{
Mc obj = new mc();
Xyz x = (xyz)obj;
Bool success = x.validate ();
Console.writeline (obj.data );
}
}
Arrays of interface types :
Interface x
{
Void get();
}
Class abc : x
{
Public void get()
{
Console.writeline("defined in abc");
}
}
Class pqr : x
{
Public void get()
{
Console.writeline("defined in pqr");
}
}
Class program
{
Static void main(string[] args)
{
X[] x1 ={ new abc(), new pqr() };
For (int i = 0; i < x1.length; i++)
X1[i].get();
}
}
Explicit interface implementation:
Interface dimension
{
Float length();
Float width();
}
Class box : dimension
{
Float lengthinches, widthinches;
Public box(float length, float width)
{
Lengthinches = length;
Widthinches = width;
}
Float dimension.length()
{
Return lengthinches;
}
Float dimension.width()
{
Return widthinches;
}
}
Class program
{
Static void main(string[] args)
{
Box mybox = new box(10.0f,12.0f);
Dimension d = (dimension )mybox;
Console.writeline(d.length());
Console.writeline(d.width());
}
}
Interface dimension1
{
Float length();
Float width();
}
Interface dimension2
{
Float length();
Float width();
}
Class box : dimension1,dimension2
{
Float lengthinches, widthinches;
Public box(float length, float width)
{
Lengthinches = length;
Widthinches = width;
}
Float dimension1.length()
{
Return lengthinches;
}
Float dimension1.width()
{
Return widthinches;
}
Float dimension2.length()
{
Return lengthinches * 10.0f;
}
Float dimension2.width()
{
Return widthinches * 20.0f;
}
Class program
{
Static void main(string[] args)
{
Box mybox = new box(10.0f,12.0f);
Dimension1 d = (dimension1 )mybox;
Dimension2 d1 = (dimension2)mybox;
Console.writeline(d.length());
Console.writeline(d.width());
Console.writeline(d1.length());
Console.writeline(d1.width());
}
}
Interface hierarchi :
One interface can inherit other interface.
Interface abc
{
Void get();
}
Interface xyz: abc
{
Void put();
}
Interface a
{
Void get();
}
Interface b : a
{
Void put();
}
Class sample : b
{
Public void get()
{
Console.writeline("first interface method defined");
}
Public void put()
{
Console.writeline("second interface method defined");
}
}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
S1.get();
S1.put();
}
Interface a
{
Void get();
}
Class b : a
{
Public void get()
{
Console.writeline("interface method defined");
}
}
Class sample : b
{
Public new void get()
{
Console.writeline("first interface method defined");
}
}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
// s1.get();
// s1.put();
((a)s1).get ();
Interface a
{
Void get();
}
Interface b : a
{
}
Class sample : b
{
Public void get()
{
Console.writeline("first interface method defined");
}
}
Class program
{
Static void main(string[] args)
{
Sample s1 = new sample();
S1.get();
}
}
Exploring the system.collection name space:
This name space contains interfaces and classes that define various
collections of objects such as lists ,queues , bit arrays, hash tables and
dictionaries.
Class
Interfaces:
Icollection defines size, enumerators and syncronization
methods.
Icomparer exposes method to compare two objects.
Idictionary represents a non generic collection of key / value
pairs.
Ienumerable returns the ienumerator interface for a given object.
Supports simple
Iteration over a non generic collection.
Ienumerator supports foreach style iteration over a non
generic collection.
Iconvertible interface :
Defines methods that convert the value of the implementing reference or
value type to a common language runtime type that has an equivalent
value.
This api is not cls-compliant.
Syntax:
Public interface iconvertible
Class program
{
Static void main(string[] args)
{
Complex m = new complex (4,7);
Display (m);
Display (convert .toboolean ());
Display(convert.tobyte ());
Display(convert.toint16 ());
Display (convert.toint64 ());
}
Static void display(object o)
{
Typecode t = type.gettypecode(o.gettype);
Switch (t)
{
Case typecode.boolean:
Console.writeline(m);
Break;
Case typecode.double:
Console.writeline(m);
Case typecode.int16:
Console.writeline(m);
Case typecode.int16:
Console.writeline(m);
Property : current
Method : movenext
Method : reset.
Ienumerable :
This interface is an interface that has one method called getenumerator() .
This method supports simple iteration over collection.
Class program
{
Static void main(string[] args)
{
Dealer d = new dealer();
Ienumerator i = d.getenumerator();
I.movenext();
Car mycar = (car)i.current;
Console.writeline(mycar.name);
Console.writeline(mycar.currsp);
}
}
}
Icloneable:
Cloning is to make an exact copy of an instance of a type.
It takes one of the two forms.
Shallow copy :
May be linked to data shared by both the original and copy.
Deep copy :
Contains the complete encapsulated data of the original object.
Class myvalue
{
Public int count ;
Public myvalue (int count)
{
This.count =count;
}
}
Class myobject : icloneable
{
Public myvalue contained;
Public myobject (int count )
{
This.contained =new myvalue (count );
}
Public object clone()
{
Console.writeline ("clone");
Return (new myobject (this.contained .count ));
}
}
Class program
{
Static void main(string[] args)
{
Myobject m =new myobject (100);
Myobject myclone =(myobject )m.clone ();
Console.writeline ("{0}{1}",m.contained .count ,myclone
.contained .count );
Myclone .contained .count =15;
Console.writeline ("{0}{1}",m.contained .count
,myclone.contained .count );
}
}
Icomparable interface :
This interface defines a comparison method to be implemented by a value
type or class.
This interface specifies a behaviour that allows an object to be sorted
based on some specified key.
Public class car:icomparable
{
Private int carid;
Public string name;
Private int currsp;
Int icomparable.compareto (object obj)
{
Car temp = (car)obj;
If(this.carid > temp.carid )
Return 1;
If(this.carid < temp.carid )
Return -1;
Else
Return 0;
}
Public int id
{
Get
{
Return carid;
}
Set
{
Carid = value;
}
}
Public car(string n, int speed, int id)
{
Carid =id;
Name =n;
Currsp =speed ;
}
Class program
{
Static void main(string[] args)
{
Car[] m = new car[5];
M[0] = new car("indica", 80, 20);
M[1] = new car("nane", 100, 10);
M[2] = new car("wagnor", 200, 30);
Foreach (car c in m)
Console.writeline("{0}{1}", c.id, c.name);
Array .sort (m );
Foreach (car c in m)
Console.writeline ("{0}{1}", c.id,c.name );
}
}
Using system.collections;
Public class student
{
Private int rollno,marks;
Private string subject;
Public string subject
{
Get
{
Return subject;
}
Set
{
Subject = value;
}
}
Class program
{
Static void main(string[] args)
{
Student[] check = new student[3];
Check[0] = new student("maths", 75, 100);
Check[1] = new student("maths", 85, 200);
Check[2] = new student("maths", 90, 300);
Array .sort (check,new student1());
Foreach( student st in check )
Console.writeline ("{0}\t\t{1}",st.rollno ,st.marks );
}
}
User can invoke c#compiler by the typing the name of its executable file
(csc.exe) on the command line.
If the user uses visual studio command prompt , all the ncessary
environment variables are set for the user.
If the user does not use visual studion prompt then vsvars32.bat to set the
appropriate environment variables to support command line builds.
Class c
{
Arraylist obj = new arraylist();
Public void putdata(a a1)
{
Obj.add(a1);
Foreach (a p in obj)
P.display();
}
Public void put(a a1)
{
// obj.remove(a1);
}
}
Class program
{
Static void main(string[] args)
{
B b1 = new b(100, 200);
C c1 = new c();
B1.display();
C1.putdata(b1);
C1.put(b1);
}
}
DELEGATES
Class program
{
Static void main(string[] args)
{
// instantiation
Displaydelegate del = new displaydelegate(displaymessage);
//invoke a delegate
Del("i was called by a delegate");
}
Class program
{
Static void main(string[] args)
{
Display a = new display(dis);
A(100);
}
Static void dis(int b)
{
Console.writeline(b);
}
}