C#dotnet Unit-3 LM
C#dotnet Unit-3 LM
Class:
Formally, a class is nothing more than a user defined type (UDT) that
is composed of data (sometimes termed as attributes or instance variables)
and behaviour or functions or member functions that act on this data (often
called methods in OOP).
Syntax:
The keyword “class” is followed by the name of the class. The opening
and closing braces contain the definition of the class. The most important
constitutes of the definition are data members and member functions. Data
members are generally implemented as variables and the member functions
as methods.
For example create a Student class with attributes name and age,
behaviour of the class contains getdata() and putdata(). Instantiate objects
to access the members of the class.
Object:
Instantiation:
The new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator also
invokes the class constructor.
In figure 3.4, s1 and s2 are the instances of the class Student. In the
main function creation of s1 and s2 requires the following code:
Output:
Enter name:
ABC
Enter age:
29
Student Details:
Name:ABC
Age:29
Enter name:
XYZ
Enter age:
20
Student Details:
Name:XYZ
Age:20
Array of objects:
Array of objects contain objects as its basic units. These arrays follow
zero-based indexing, that is, the first element will have index zero. For
example, in the following declaration, the names of the various elements in
the array will be stu[0], stu[1], stu[2], stu[4] (Figure 3.5).
Syntax:
Name of the class[ ] name of the array = new Name of the class[ ];
Example:
{
Console.WriteLine("Student Details: ");
Console.WriteLine("\tName:{0}", name);
Console.WriteLine("\tAge:{0}", age);
}
}
Output:
Enter number of students: 3
Enter details
Enter name: ABC
Enter age: 29
Enter details
Enter name: XYZ
Enter age: 20
The details of the students are as follows:
Student Details:
Name: ABC
Age: 29
Student Details:
Name: XYZ
Age: 20
1. Default Constructor:
2. Parameterized Constructor:
Parameterized Constructor is a constructor that has arguments. It has no
return type and has the same name as that of its class of which it is a
constructor. It can initialize each instance of the class to different values.
Example program for Parameterized Constructor:
using System;
namespace DCon1
{
public class Program
{
public class Student
{
string name;
int age;
Student(String s,int a) //Parameterized Constructor
{
name=s;
age=a;
}
public void putdata()
{
Console.WriteLine("Student Details: ");
Console.WriteLine("\tName:{0}", name);
Console.WriteLine("\tAge:{0}", age);
}
}
public static void Main(string[] args)
{
Student s1=new Student(“Alice”,20);
s1.putdata();
Student s2=new Student(“John”,22);
s2.putdata();
}
}
}
Output:
Student Details:
Name: Alice
Age: 20
Student Details:
Name: John
Age: 22
3. Copy Constructor:
Output:
Student Details:
Name: John
Age: 22
4. Private Constructor:
using System;
namespace PrivateConstructor
{
class Program
{
public class PCStudent
{
private PCStudent() //Private Constructor
{
Console.WriteLine("Private Constructor");
}
}
“this” reference:
In c#, this keyword is used to refer the current instance of class and
by using this keyword we can pass current instance of class as a parameter
to the other methods.
We can also use this keyword to declare indexers and to specify the
instance variable in the parameter list of an extension method.
In c#, we should not use this keyword to refer static field or method
and also it cannot used in static classes.
using System;
namespace n1
{
class Student
{
// instance member
public string name;
public string getname()
{
return name;
}
public void setname(string name)
{
// referring to current instance
//"this.Name" refers to class member
this.name = name;
}
}
class program
{
public static void Main()
{
Student obj = new Student();
obj.setname("Welcome to New World");
Console.WriteLine(obj.getname());
}
}
}
Output:
Welcome to New World
2: Program using this() to invoke the constructor in same class:
using System;
namespace TUStudent2
{
class TUStu2
{
public TUStu2() : this("Hello")
{
Console.WriteLine("Non-Parameter Constructer Called");
}
// Declare Parameter Constructer
public TUStu2(string name)
{
Console.WriteLine("{0}",name);
}
static void Main(string[] args)
{
TUStu2 obj = new TUStu2();
}
}
}
Output:
Hello
Non-Parameter Constructer Called
3: Program using ‘this’ keyword to invoke current class method
using System;
namespace TUStu3
{
class TUStudent3
{
void display()
{
// calling fuction show()
this.show();
Output:
Sun Mon Tue Wed Thu Fri Sat
Static members:
Static members are those members for which only one copy is created. If we
have a static method, then it can use only those members that are static.
Moreover, they are called by the name of the class not by the object of the
class.
Static Class
A static class is declared with the help of static keyword. A static class can
only contain static data members, static methods, and a static constructor.
It is not allowed to create objects of the static class. Static classes
are sealed, means one cannot inherit a static class from another class.
Note: Static class, methods, variables can be directly accessed with class
name without creating object to the class.
class name.variablename();
class name.methodname();
Example program for Static members:
using System;
namespace SMProgram
{
class SMProgram
{
static int i = 10;
void modify()
{
i = i + 2;
Console.WriteLine("i value inside non-static method function:{0}",i);
}
static void display()
{
Console.WriteLine("i value in static method:{0}",SMProgram.i);
}
static void Main(string[] args)
{
SMProgram s1 = new SMProgram();
s1.modify();
SMProgram.display();
}
}
}
Output:
i value inside non-static method function:12
i value in static method:12
(or)
The process of out is unidirectional i.e. we don't have to supply value to the
formal parameters but we get back processed value.
We use this process when we want some parameters to bring back some
processed values form the called method.
(or)
The out parameters are the parameters that are passed as arguments of a
method but are set by the methods themselves. They are, in fact, the
outcome of the execution of a method. They pass the result back to the
method that calls the method. The parameters are preceded by the keyword
“out”.
The params keyword lets you specify a method parameter that takes an
argument where the number of arguments is variable.
namespace ParPassingSParam
{
class PPSParam
{
class Sample
{
public void display(params int[] n)
{
foreach(int x in n)
{
Console.Write(" " + x);
}
}
}
static void Main(string[] args)
{
int[] n = {1,2,3,4,5,6};
int a = 10, b = 20, c = 30, d = 40;
Sample s1 = new Sample();
s1.display(a, b, c, d);
s1.display(n);
Console.ReadLine();
}
}
}
Output:
10 20 30 40 1 2 3 4 5 6
An object is passed in the same way as basic data type. However, care must
be taken to ensure that the objects are initialized before passing them to a
function. The following listing passes the object of the class ABC to a
method display(). It should be noted that display() is deliberately declares as
static, so that there is just one copy of display() in the program class and the
function can be called without making an instance of POFun.
9. Components of a class:
Constructor Properties
Destructor Indexers
Constants Operators
Fields Events
Methods Delegates
Classes Structures
Interfaces
10. Properties:
Properties are the mechanisms to read and write the values of objects.
11. Indexers:
An indexer is used to access the objects with the help of the index
notation. It is written in the same way as a property. It is declared in the
following way:
public type this [int index]
Example program:
using System;
namespace TUStu5
{
class TUStudent5
{
private string[] days = new string[7];
// declaring an indexer
public string this[int index]
{
get
{
return days[index];
}
set
{
days[index] = value;
}
}
static void Main(string[] args)
{
TUStudent5 g = new TUStudent5();
g[0] = "Sun";
g[1] = "Mon";
g[2] = "Tue";
g[3] = "Wed";
g[4] = "Thu";
g[5] = "Fri";
g[6] = "Sat";
for (int i = 0; i < 7; i++)
Console.Write(g[i] + " ");
}
}
}
Visibility controls in C#:
1. Public.
2. Private.
3. Protected.
4. Internal.
5. Protected internal.
1. Public:
Public is the most common access specifier in C#. It can be access from
anywhere that means there is no restriction on accessibility. The scope of
the accessibility is inside class as well as outside. The type or member can
be accessed by any other code in the same assembly or another assembly
that references it.
Example program:
using System;
namespace ConsoleApplication1
{
class PublicAccess
{
public string msg = "This variable is public";
public void disp(string msg)
{
Console.WriteLine("This function is public : " + msg);
}
}
class Program
{
static void Main(string[] args)
{
PublicAccess pAccess = new PublicAccess();
Console.WriteLine(pAccess.msg); // Accessing public variable
pAccess.disp("Hello !!"); // Accessing public function
}
}
}
Output:
This variable is public
This function is public : Hello !!
2. Private:
The scope of the accessibility is limited only inside the classes or struct in
which they are declared. The private members cannot be accessed outside
the class and it is the least permissive access level.
Example program:
using System;
namespace ConsoleApplication1
{
class Program
{
private string msg = "This variable is private ";
private void disp(string msg)
{
Console.WriteLine("This function is private : " + msg);
}
static void Main(string[] args)
{
Program pr = new Program();
Console.WriteLine(pr.msg);// / Accessing private variable inside the
class
pr.disp("Hello !!"); // Accessing private function inside the class
}
}
}
Output:
This variable is private
This function is private : Hello !!
3. Protected:
The scope of accessibility is limited within the class or struct and the class
derived (Inherited) from this class.
Example program:
using System;
namespace ConsoleApplication1
{
class ProtectedAccess
{
protected string msg = "This variable is protected ";
protected void disp(string msg)
{
Console.WriteLine("This function is protected : " + msg);
}
}
class Program : ProtectedAccess
{
static void Main(string[] args)
{
Program pr = new Program();
Console.WriteLine(pr.msg); // Accessing protected variable
pr.disp("Hello !!"); // Accessing protected function
}
}
}
Output:
This variable is protected
This function is protected : Hello !!
4. Internal:
The internal access modifiers can access within the program that contain its
declarations and also access within the same assembly level but not from
another assembly.
Example program:
using System;
namespace ConsoleApplication1
{
class InternalAccess
{
internal string msg = "This variable is internal";
internal void disp(string msg)
{
Console.WriteLine("This function is internal : " + msg);
}
}
class Program
{
static void Main(string[] args)
{
InternalAccess iAccess = new InternalAccess();
Console.WriteLine(iAccess.msg); // Accessing internal variable
iAccess.disp("Hello !!"); // Accessing internal function
Console.ReadKey();
}
}
}
Output:
This variable is internal
This function is internal : Hello !!
5. Protected internal:
Protected internal is the same access levels of both protected and internal. It
can access anywhere in the same assembly and in the same class also the
classes inherited from the same class.
Example program:
using System;
namespace ConsoleApplication1
{
class InternalAccess
{
protected internal string msg = "This variable is protected internal";
protected internal void disp(string msg)
{
Console.WriteLine("This function is protected internal : " + msg);
}
}
class Program
{
static void Main(string[] args)
{
InternalAccess iAccess = new InternalAccess();
Console.WriteLine(iAccess.msg); // Accessing internal variable
iAccess.disp("Hello !!"); // Accessing internal function
Console.ReadKey();
}
}
}
Output:
This variable is protected internal
This function is protected internal : Hello !!