OOPS Concepts
Class:
It is a collection of objects.
Object:
It is a real time entity.
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address. In pure OOP terms an object is an instance of a class
The above template describe about object Student
Class is composed of three things name, attributes, and operations
public class student
{
}
student objstudent=new student ();
According to the above sample we can say that Student object, named objstudent, has created out of the student class.
In real world you will often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the Textbox control, you always used, is made out of theTextbox class, which defines its appearance and capabilities. Each time you drag a Textbox control, you are actually creating a new instance of the Textbox class.
Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class
public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}
In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier
Abstraction:
Abstraction is a process of hiding the implementation details and displaying the essential features.
Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works. You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers
.Net has five access Specifiers
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
Let’s try to understand by a practical example:-
public class Class1
{
int i; //No Access specifier means private
public int j; // Public
protected int k; //Protected data
internal int m; // Internal means visible inside assembly
protected internal int n; //inside assembly as well as to derived classes outside assembly
static int x; // This is also private
public static int y; //Static means shared across objects
[DllImport("MyDll.dll")]
public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly
public void myFoo2()
{
//Within a class if you create an object of same class then you can access all data members through object reference even private data too
Class1 obj = new Class1();
obj.i =10; //Error can’t access private data through object.But here it is accessible.:)
obj.j =10;
obj.k=10;
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10;
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
}
Now lets try to copy the same code inside Main method and try to compile
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
obj.m=10;
obj.n=10;
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
What if Main is inside another assembly
[STAThread]
static void Main()
{
//Access specifiers comes into picture only when you create object of class outside the class
Class1 obj = new Class1();
// obj.i =10; //Error can’t access private data through object.
obj.j =10;
// obj.k=10; //Error can’t access protected data through object.
// obj.m=10; // Error can’t access internal data outside assembly
// obj.n=10; // Error can’t access internal data outside assembly
// obj.s =10; //Errror Static data can be accessed by class names only
Class1.x = 10; //Error can’t access private data outside class
// obj.y = 10; //Errror Static data can be accessed by class names only
Class1.y = 10;
}
In object-oriented software, complexity is managed by using abstraction.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.
Inheritance:
Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary concepts of object-oriented programming. It allows you to reuse existing code. Through effective use of inheritance, you can save lot of time in your programming and also reduce errors, which in turn will increase the quality of work and productivity. A simple example to understand inheritance in C#.
Using System;
Public class BaseClass
{
Public BaseClass ()
{
Console.WriteLine ("Base Class Constructor executed");
}
Public void Write ()
{
Console.WriteLine ("Write method in Base Class executed");
}
}
Public class ChildClass: BaseClass
{
Public ChildClass ()
{
Console.WriteLine("Child Class Constructor executed");
}
Public static void Main ()
{
ChildClass CC = new ChildClass ();
CC.Write ();
}
}
In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.
The output of the above program is
Output:
Output:
Base Class Constructor executed
Child Class Constructor executed
Write method in Base Class executed
Child Class Constructor executed
Write method in Base Class executed
this output proves that when we create an instance of a child class, the base class constructor will automatically be called before the child class constructor. So in general Base classes are automatically instantiated before derived classes.
In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The base class is specified by adding a colon, ":", after the derived class identifier and then specifying the base class name.
Syntax: class ChildClassName: BaseClass
{
//Body
}
{
//Body
}
C# supports single class inheritance only. What this means is, your class can inherit from only one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B at the same time. This is not allowed in C#. This will lead to a compile time
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.
public class A
{
}
public class B
{
}
public class C : A, B
{
}
In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have access to all members present in both Class A and Class B. As a result of multi-level inheritance Class has access to A_Method(),B_Method() and C_Method().
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.
Note: Classes can inherit from multiple interfaces at the same time. Interview Question: How can you implement multiple inheritance in C#? Ans : Using Interfaces. We will talk about interfaces in our later article.
Using System;
Public class A
{
Public void A_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class B: A
{
Public void B_Method ()
{
Console.WriteLine ("Class A Method Called");
}
}
Public class C: B
{
Public void C_Method ()
{
Console.WriteLine ("Class A Method Called");
}
Public static void Main ()
{
C C1 = new C ();
C1.A_Method ();
C1.B_Method ();
C1.C_Method ();
}
}
When you derive a class from a base class, the derived class will inherit all members of the base class except constructors. In the code snippet below class B will inherit both M1 and M2 from Class A, but you cannot access M2 because of the private access modifier. Class members declared with a private access modifier can be accessed only with in the class. We will talk about access modifiers in our later article.Common Interview Question: Are private class members inherited to the derived class?
Ans: Yes, the private members are also inherited in the derived class but we will not be able to access them. Trying to access a private base class member in the derived class will report a compile time error.
Using System;
Public class A
{
Public void M1 ()
{
}
Private void M2 ()
{
}
}
Public class B: A
{
Public static void Main ()
{
B B1 = new B ();
B1.M1 ();
//Error, Cannot access private member M2
//B1.M2 ();
}
}
Method Hiding and Inheritance We will look at an example of how to hide a method in C#. The Parent class has a write () method which is available to the child class. In the child class I have created a new write () method. So, now if I create an instance of child class and call the write () method, the child class write () method will be called. The child class is hiding the base class write () method. This is called method hiding.
If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.
If we want to call the parent class write () method, we would have to type cast the child object to Parent type and then call the write () method as shown in the code snippet below.
Using System;
Public class Parent
{
Public void Write ()
{
Console.WriteLine ("Parent Class write method");
}
}
Public class Child: Parent
{
Public new void Write ()
{
Console.WriteLine ("Child Class write method");
}
Public static void Main ()
{
Child C1 = new Child ();
C1.Write ();
//Type caste C1 to be of type Parent and call Write () method
((Parent) C1).Write ();
}
}
Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features:
- It allows you to invoke methods of derived class through base class reference during runtime.
- It has the ability for classes to provide different implementations of methods that are called through the same name.
Polymorphism is of two types:
- Compile time polymorphism/Overloading
- Runtime polymorphism/Overriding
Compile Time Polymorphism
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Runtime Time Polymorphism
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism. It is also called late binding.
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different, unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void area(int side);
void area(int l, int b);
void area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace method_overloading
{
class Program
{
public class Print
{
public void display(string name)
{
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
static void Main(string[] args)
{
Print obj = new Print ();
obj.display ("George");
obj.display (34, 76.50f);
Console.ReadLine ();
}
}
}
Note: In the code if you observe display method is called two times. Display method will work according to the number of parameters and type of parameters.
When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing.
Method overloading showing many forms.
using System;
namespace method_overloading_polymorphism
{
Class Program
{
Public class Shape
{
Public void Area (float r)
{
float a = (float)3.14 * r;
// here we have used function overload with 1 parameter.
Console.WriteLine ("Area of a circle: {0}",a);
}
Public void Area(float l, float b)
{
float x = (float)l* b;
// here we have used function overload with 2 parameters.
Console.WriteLine ("Area of a rectangle: {0}",x);
}
public void Area(float a, float b, float c)
{
float s = (float)(a*b*c)/2;
// here we have used function overload with 3 parameters.
Console.WriteLine ("Area of a circle: {0}", s);
}
}
Static void Main (string[] args)
{
Shape ob = new Shape ();
ob.Area(2.0f);
ob.Area(20.0f,30.0f);
ob.Area(2.0f,3.0f,4.0f);
Console.ReadLine ();
}
}
}
Things to keep in mind while method overloading
If you use overload for method, there are couple of restrictions that the compiler imposes.
The rule is that overloads must be different in their signature, which means the name and the number and type of parameters.
There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.
Method Overriding:
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.
Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.
Example:
// Base classpublic class BaseClass
{
public virtual void Method1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Method1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass();
objDC.Method1();
// calling the baesd class method
BaseClass objBC = (BaseClass)objDC;
objDC.Method1();
}
}
Output
---------------------
Derived Class Method
Derived Class Method
Constructors and Destructors:
Classes have complicated internal structures, including data and functions, object initialization and cleanup for classes is much more complicated than it is for simple data structures. Constructors and destructors are special member functions of classes that are used to construct and destroy class objects. Construction may involve memory allocation and initialization for objects. Destruction may involve cleanup and deallocation of memory for objects.
- Constructors and destructors do not have return types nor can they return values.
- References and pointers cannot be used on constructors and destructors because their addresses cannot be taken.
- Constructors cannot be declared with the keyword virtual.
- Constructors and destructors cannot be declared const, or volatile.
- Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if you declare a constructor with protected access, only derived classes and friends can use it to create class objects.
The compiler automatically calls constructors when defining class objects and calls destructors when class objects go out of scope. A constructor does not allocate memory for the class object it’s this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the newoperator. During cleanup, a destructor may release objects allocated by the corresponding constructor. To release objects, use the delete operator.
class C
Example of Destructor
{
private int x;
private int y;
public C (int i, int j)
{
x = i;
y = j;
}
public void display ()
{
Console.WriteLine(x + "i+" + y);
}
}Example of Destructor
class D
{
public D ()
{
// constructor
}
~D ()
{
// Destructor
}
}
OOPS Features in brief
Output
A = 10 B = 20
A = 80 B = 40
Copy Constructor : A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.
Example for Copy Constructor
Output
A = 80 B = 90
A = 80 B = 90
Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
Example for Static Constructor
Output
Static Constructor
Instance Constructor
Instance Constructor
Static Class in .NET
Example Program for
Static class in C#
Output
Now you can access field directly with class name as it is static and public
Classes in .NET
Members of a Class
Example for Class in
.NET
C# Access Modifier
Private: Private members of a class are completely restricted and are accessible only within the class in which they are declared.
What is Return Type
C#.NET Return Type
Example
Example Program for Continue in c#
Output
1
2
3
5
6
7
8
9
10
In the above output, you can see the number 4 is not printed.
.NET C# Arrays
One Dimensional Arrays
in C#
Syntax : DataType[] ArrayName = new DataType[Size];
Example
In C#, Array can be declared and initialized at a time as below
The following code declares and initializes an array of 5 string items.
string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
You can initialize a dynamic length array as follows:
string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
OOPS Features in brief
The programming in which data is logically
represented in the form of a class and physically represented in the form an
object is called as object oriented programming (OOP). OOP has the following
important features.
Class : In OOP
languages it is must to create a class for representing data. Class containsvariables
for storing data and functions to specify various operations that can be
performed on data. Class will not occupy any memory space and hence it is only
logical representation of data.
Classes in .NET
Classes in .NET
Data Encapsulation :Within a class
variables are used for storing data and functions to specify various
operations that can be performed on data. This process of wrapping up of data
and functions that operate on data as a single unit is called as data
encapsulation.
Data Abstraction : Within a
class if a member is declared as private, then that
member can not be
accessed from out side the class. I.e. that member is hidden from rest of the
program. This process of hiding the details of a class from rest of the program
is called as data abstraction. Advantage of data abstraction is security.
Object And Instance : Class will
not occupy any memory space. Hence to work with the data represented by the
class you must create a variable for the class, which is called as an object.
When an object is created by using the keyword new, then memory will be allocated for the class in heap
memory area, which is called as an instance and its starting address will be
stored in the object in stack memory area.
When an object is created without the
keyword new, then memory will not be allocated in heap I.e. instance will not be
created and object in the stack contains the value null. When
an object contains null, then it is not possible to access the members of the
class using that object.
Inheritance : Creating a
new class from an existing class is called as inheritance. When a new class requires same
members as an existing class, then instead of recreating those members the new
class can be created from existing class, which is called as inheritance.
Advantage of inheritance is reusability of the code. During inheritance, the class
that is inherited is called as base class and the class that does the
inheritance is called as derived class.
Inheritance in .NET
Different Types of Inheritance
Inheritance in .NET
Different Types of Inheritance
Polymorphism : Polymorphism
means having more than one form. Polymorphism can be achieved with the help
of overloading and overriding concepts. Polymorphism is classified into compile
time polymorphism and runtime polymorphism.
Constructor types with example programs in C#.NET
A special method of the class that will be automatically
invoked when an instance of the class is created is called as constructor.
Constructors can be classified into 5 types
Constructors can be classified into 5 types
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Default Constructor : A constructor without any parameters is called as
default constructor. Drawback of default constructor is every instance of the
class will be initialized to same values and it is not possible to initialize
each instance of the class to different values.
Example for Default Constructor
Parameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.
Example for Parameterized Constructor
Example for Default Constructor
Parameterized Constructor : A constructor with at least one parameter is called as parameterized constructor. Advantage of parameterized constructor is you can initialize each instance of the class to different values.
Example for Parameterized Constructor
using System;
namespace ProgramCall
{
class Test1
{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}
}
}
namespace ProgramCall
{
class Test1
{
//Private fields of class
int A, B;
//default Constructor
public Test1()
{
A = 10;
B = 20;
}
//Paremetrized Constructor
public Test1(int X, int Y)
{
A = X;
B = Y;
}
//Method to print
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class MainClass
{
static void Main()
{
Test1 T1 = new Test1(); //Default Constructor is called
Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called
T1.Print();
T2.Print();
Console.Read();
}
}
}
Output
A = 10 B = 20
A = 80 B = 40
Copy Constructor : A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.
Example for Copy Constructor
using System;
namespace ProgramCall
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = new Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
namespace ProgramCall
{
class Test2
{
int A, B;
public Test2(int X, int Y)
{
A = X;
B = Y;
}
//Copy Constructor
public Test2(Test2 T)
{
A = T.A;
B = T.B;
}
public void Print()
{
Console.WriteLine("A = {0}\tB = {1}", A, B);
}
}
class CopyConstructor
{
static void Main()
{
Test2 T2 = new Test2(80, 90);
//Invoking copy constructor
Test2 T3 = new Test2(T2);
T2.Print();
T3.Print();
Console.Read();
}
}
}
Output
A = 80 B = 90
A = 80 B = 90
Static Constructor : You can create a constructor as static and when a constructor is created as static, it will be invoked only once for any number of instances of the class and it is during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.
Example for Static Constructor
using System;
namespace ProgramCall
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
//Static Constructor and instance constructor, both are invoked for first instance.
Test3 T1 = new Test3();
//Only instance constructor is invoked.
Test3 T2 = new Test3();
Console.Read();
}
}
}
namespace ProgramCall
{
class Test3
{
public Test3()
{
Console.WriteLine("Instance Constructor");
}
static Test3()
{
Console.WriteLine("Static Constructor");
}
}
class StaticConstructor
{
static void Main()
{
//Static Constructor and instance constructor, both are invoked for first instance.
Test3 T1 = new Test3();
//Only instance constructor is invoked.
Test3 T2 = new Test3();
Console.Read();
}
}
}
Output
Static Constructor
Instance Constructor
Instance Constructor
Private Constructor : You can
also create a constructor as private. When a class contains at
least one private constructor, then it is not possible to create an instance
for the class. Private constructor is used to restrict the class from being
instantiated when it contains every member as static.
Some unique points related to constructors are as follows
Some unique points related to constructors are as follows
- A class can have any number of constructors.
- A constructor doesn’t have any return type even void.
- A static constructor can not be a parameterized constructor.
- Within a class you can create only one static constructor.
Static Class in .NET
If you want to restrict the class from instantiated
, you can declare the class as static class.
Example Program for
Static class in C#
using System;
//Static
Class
static class programcall
{
public static string str;
public static void print()
{
Console.WriteLine(str);
}
}
//Using
Static class in the program
class MainClass
{
public static void Main()
{
programcall.str = "Now you can access field directly with class name as it is static
and public";
programcall.print();
Console.Read();
}
}
Output
Now you can access field directly with class name as it is static and public
Classes in .NET
A class in .NET can be
created with only two access modifiers, public and internal.
Default is public. When a class is declared as public, it can be accessed within the same assembly in which it was declared as well as from out side the assembly.
But when the class is created as internal then it can be accessed only within the same assembly in which it was declared.
To create a class, use the keyword class and has the following syntax.
Default is public. When a class is declared as public, it can be accessed within the same assembly in which it was declared as well as from out side the assembly.
But when the class is created as internal then it can be accessed only within the same assembly in which it was declared.
To create a class, use the keyword class and has the following syntax.
[Access Modifier] class
ClassName
{
-
-
-
}
Members of a Class
A class can have any of the following members.
- Fields
- Properties
- Methods
- Events
- Constructors
- Destructor
- Operators
- Indexers
- Delegates
Fields : A
field is the variable created within the class and it is used to store data of
the class. In general fields will be private to the class for providing
security for the data
Syntax : [Access
Modifier] DataType Fieldname;
Properties : A
property is a method of the class that appears to the user as a field of the
class. Properties are used to provide access to the private fields of the
class. In general properties will be public.
Syntax
: [Access Modifier] DataType PropName
{
Get
{
}
Set
{
}
}
A property
contains two accessors, get and set.
When user assigns a value to the property, the set accessor of the property will be automatically invoked and value assigned to the property will be passed to set accessor with the help of an implicit object called value. Hence set accessor is used to set the value to private field. Within the set accessor you can perform validation on value before assigning it to the private field.
When user reads a property, then the get accessor of the property is automatically invoked. Hence get accessor is used to write the code to return the value stored in private field.
When user assigns a value to the property, the set accessor of the property will be automatically invoked and value assigned to the property will be passed to set accessor with the help of an implicit object called value. Hence set accessor is used to set the value to private field. Within the set accessor you can perform validation on value before assigning it to the private field.
When user reads a property, then the get accessor of the property is automatically invoked. Hence get accessor is used to write the code to return the value stored in private field.
Readonly
Property : There may be a situation where you want to
allow the user to read the property and not to assign a value to the property.
In this case property has to be created as readonly property and for this
create the property only with get accessor without set accessor.
Syntax : [Access
Modifier] DataType PropName
{
Get
{
}
}
Writeonly Property : There
may be a situation where you want to allow the user to assign a value to the
property and not to read the property. In this case property has to be created
as writeonly property and for this create the property only with set accessor
without get accessor.
Syntax : [Access
Modifier] DataType PropName
{
Set
{
}
}
Methods
Methods are nothing but functions created
within the class. Functions are used to specify various operations that can be
performed on data represented by the class.
Example for Class in
.NET
//C# class for Box
class Box
{
//Private
fields
private int length;
private int width;
private int heigth;
//Constructor
public Box(int length, int width, int height)
{
this.Length
= length;
this.Width
= width;
this.Heigth
= height;
}
//Properties
public int Length
{
get { return length; }
set { length = value;
}
}
public int Width
{
get { return width; }
set { width = value;
}
}
public int Heigth
{
get { return heigth; }
set { heigth = value;
}
}
//Method
public int Volume()
{
return this.Length
* this.Width
* this.Heigth;
}
}
C# Access Modifier
Different Access Modifiers in C# are Public, Private,
Protected, internal, protected internal.Default access modifier for members of
class is private.
Default Access Modifiers in C#
Namespace will not have access modifier.
Default access modifier for class ,struct, Interface, Enum, Delegate is Internal.
Default access modifier for class and struct members is private.
No access modifier can be applied to interface members and always interface members are public.
Enum members are always public and no access modifier can be applied.
Access Modifier Basics
An access modifier is a keyword of the language that is used to specify the access level of members of a class. C#.net supports the following access modifiers.
Default Access Modifiers in C#
Namespace will not have access modifier.
Default access modifier for class ,struct, Interface, Enum, Delegate is Internal.
Default access modifier for class and struct members is private.
No access modifier can be applied to interface members and always interface members are public.
Enum members are always public and no access modifier can be applied.
Access Modifier Basics
An access modifier is a keyword of the language that is used to specify the access level of members of a class. C#.net supports the following access modifiers.
Public: When Members of a class are declared as public, then they
can be accessed
1. Within
the class in which they are declared.
2. Within
the derived classes of that class available within the same assembly.
3. Outside
the class within the same assembly.
4. Within
the derived classes of that class available outside the assembly.
5. Outside
the class outside the assembly.
Internal: When Members of a class are declared as internal, then
they can be accessed
1. Within
the class in which they are declared.
2. Within
the derived classes of that class available within the same assembly.
3. Outside
the class within the same assembly.
Protected: When
Members of a class are declared as
protected, then they can beaccessed
1. Within the class in which they are
declared.
2. Within the derived classes of that
class available within the same assembly.
3. Within the derived classes of that
class available outside the assembly.
Protected internal: When
Members of a class are declared as protected internal, then they can be accessed
1. Within
the class in which they are declared.
2. Within
the derived classes of that class available within the same assembly.
3. Outside
the class within the same assembly.
4. Within
the derived classes of that class available outside the assembly.
Private: Private members of a class are completely restricted and are accessible only within the class in which they are declared.
What is Return Type
Return Type specifies the output type
of a function.
The output type can be a number,text etc..
If output of function is a number, the return type may be int or float or decimal etc..
If output of function type is text, the return type will be string etc..
The output type( return type ) can be a user defined class or struct or interface or enum or any type.
The output type can be a number,text etc..
If output of function is a number, the return type may be int or float or decimal etc..
If output of function type is text, the return type will be string etc..
The output type( return type ) can be a user defined class or struct or interface or enum or any type.
C#.NET Return Type
Example
using System;
//Sample
program to demonstrate return types
//Request
user to input 2 numbers and print the sum
namespace ProgramCall
{
class Program
{
static void Main(string[]
args)
{
int num1 = 0;
int num2 = 0;
Console.WriteLine("Enter any
2 numbers ");
//Console.Readline
returns of type string , so converting it to int.
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
//The
function FindSum returns of type int so we are storing it in int
variable.
int sum =
FindSum(num1, num2);
Console.WriteLine("Sum
of {0} and {1} is {2} ",
num1, num2, sum);
Console.ReadLine();
}
//The
function outputs of type integer, so return type is declared as int.
private static int FindSum(int x, int y)
{
return (x + y);
}
}
}
Output of above
return type sample
Enter any 2 numbers
45
80
Sum of 45 and 80 is 125
Enter any 2 numbers
45
80
Sum of 45 and 80 is 125
Continue
will skip execution of statements in the loop for once and continue the loop
Example Program for Continue in c#
using System;
//Program
to print numbers 1 to 10 skipping number 4 using for loop
namespace ProgramCall
{
class ContinueExample
{
static void Main()
{
//For
loop to print numbers
for (int num = 1; num <=
10; num++)
{
//if num is equal
to 4 , don't print
if (num == 4)
continue;
//if num is 4
below statement will not be executed.
//print the number
on console.
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
Output
1
2
3
5
6
7
8
9
10
In the above output, you can see the number 4 is not printed.
.NET C# Arrays
An array is a variable that can store more than one value
of same data type.
A normal variable can store only one value and when you want to store more than one value in a variable then declare that variable as an array.
In C# array element index starts with zero and ends with size -1 same as in case of an array in C.
A normal variable can store only one value and when you want to store more than one value in a variable then declare that variable as an array.
In C# array element index starts with zero and ends with size -1 same as in case of an array in C.
One Dimensional Arrays
in C#
Syntax : DataType[] ArrayName = new DataType[Size];
Example
int[]
digits = new int[10];
String[] names = new string[10];
object[]
objects = new Object[10];
In C#, Array can be declared and initialized at a time as below
//Int
Array
int[]
digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//String
Array
string[]
names = { "John", "Bill", "Harry" };
//Char
Array
char[]
chararray = { 'a', 'b', 'c', 'd', 'e', 'f' };
string[] myColors = {"red", "green", "yellow", "orange", "blue"};
System.Array.Sort (myColors);
for (int i=0; i<myColors.Length; i++)
{
System.Console.WriteLine(myColors[i]);
}
System.Array.Reverse (myColors);
for (int i=0; i<myColors.Length; i++)
{
System.Console.WriteLine(myColors[i]);
}
System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(3);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining in Redmond.");
int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list)
{
t += x;
}
// String arrays with 3 elements:
string[] arr1 = new string[] { "one", "two", "three" };
string[] arr2 = { "one", "two", "three" };
var arr3 = new string[] { "one", "two", "three" };
string[] arr4 = new string[3];
arr4[0] = "one";
arr4[1] = "two";
arr4[2] = "three";
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
int[] array = new int[] {2, 4, 5, 6, 7, 3, 2 };
foreach (int i in array)
{
Console.WriteLine(i);
}
int[] array = new int[] {2, 4, 5, 6, 7, 3, 2 };
foreach (int i in array)
{
Console.WriteLine(i);
}
The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};
The following code declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
You can even directly assign these values without using the new operator.
string[] strArray = { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
You can initialize a dynamic length array as follows:
string[] strArray = new string[] { "Mahesh", "Mike", "Raj", "Praveen", "Dinesh" };
Simple Program
using System;
public class CSharpApp
{
static void Main()
{
int[,] twodim = new int[,] { { 1, 2, 3 }, { 1, 2, 3 } };
int d1 = twodim.GetLength(0);
int d2 = twodim.GetLength(1);
for (int i = 0; i < d1; i++)
{
for (int j = 0; j < d2; j++)
{
Console.WriteLine(twodim[i, j]);
}
}
}
}
using System;
using System.Collections;
class Program
{
static void Main()
{
//
// Create an ArrayList and add two ints.
//
ArrayList list = new ArrayList();
list.Add(5);
list.Add(7);
//
// Use ArrayList with method.
//
Example(list);
}
static void Example(ArrayList list)
{
foreach (int i in list)
{
Console.WriteLine(i);
Console.ReadKey();
}
}
}
Output
3
4
5
6
using System;
using System.Collections;
class Program
{
static void Main()
{
//
// Create an ArrayList with 4 strings.
//
ArrayList list = new ArrayList();
list.Add("DotNet");
list.Add("Java");
list.Add("PHP");
list.Add("SQL");
//
// Get last two elements in ArrayList.
//
ArrayList range = list.GetRange(2, 2);
//
// Display the elements.
//
foreach (string val in range)
{
Console.WriteLine(val);
Console.ReadKey();
}
}
}
OutPut:
PHP
SQL
No comments:
Post a Comment