Unit Ii
Unit Ii
UNIT-II
BY
return name;
} }
set }
{
name = value; Output:
} Employee Name: Sonoo Jaiswal
}
C# indexer
• A C# indexer is a class property that allows you to access a member variable
of a class or struct using the features of an array.
Syntax:
[access_modifier] [return_type] this [argument_list] {
get { // get block code
}
set { // set block code
}
}
In the above syntax:
• access_modifier: It can be public, private, protected or internal.
• return_type: It can be any valid C# type.
• this: It is the keyword which points to the object of the current class.
• argument_list: This specifies the parameter list of the indexer.
• get{ } and set { }: These are the accessors.
using System; set {
if( index >= 0 && index <= size-1 ) {
namespace IndexerApplication { namelist[index] = value;
}
class IndexedNames { }
private string[] namelist = new string[size]; }
static public int size = 10; static void Main(string[] args) {
IndexedNames names = new IndexedNames();
public IndexedNames() { names[0] = "Zara";
for (int i = 0; i < size; i++) names[1] = "Riz";
namelist[i] = "N. A."; names[2] = "Nuha";
} names[3] = "Asif";
public string this[int index] { names[4] = "Davinder";
get { names[5] = "Sunil";
string tmp; names[6] = "Rubic";
if( index >= 0 && index <= size-1 ) { for ( int i = 0; i < IndexedNames.size; i++ ) {
tmp = namelist[index]; Console.WriteLine(names[i]);
} else { }
tmp = ""; Console.ReadKey();
} }
}
return ( tmp ); }
}
Access Specifiers
• Access Specifiers defines the scope of a class member. A
class member can be variable or function.
• In C# there are five types of access specifiers are available.
Type Access Specifiers:
1.Public Access Specifiers
2.Private Access Specifiers
3.Protected Access Specifiers
4.Internal Access Specifiers
5.Protected Internal Access Specifiers.
• Private Modifier
• If we declare a field with a private access modifier, it can only
be accessed within the same class.
class Car
{
private string model = "Mustang";
static void Main(string[] args)
{
Car myObj = new Car(); Console.WriteLine(myObj.model);
}
}
• Public Modifier
• If you declare a field with a public access modifier, it is
accessible for all classes:
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}}
• protected
• Access is limited to the class that contains the member and derived
types of this class.
• It means a class which is the subclass of the containing class
anywhere in the program can access the protected members.
• Syntax:
• protected TypeName
• internal
• Access is limited to only the current Assembly, that is any class or
type declared as internal is accessible anywhere inside the same
namespace. It is the default access modifier in C#.
• internal TypeName
• protected internal
• Access is limited to the current assembly or the derived types of
the containing class. It means access is granted to any class
which is derived from the containing class within or outside the
current Assembly.
• protected internal TypeName
• private protected
• Access is granted to the containing class and its derived types
present in the current assembly. This modifier is valid in C#
version 7.2 and later.
• private protected TypeName
Methods
• A method is a group of statements that together perform
a task.
Methods
Type of Methods According parameter methods are
divided into two types:
• Parameterized method
• Parameter less method
According to return type Methods are divide into two
types:
• Void Method
• Non-void Method
Parameter less method
• The constructor of a class must have the same name as the class
name in which it resides.
• A constructor can not be abstract, final, and Synchronized.
• A constructor doesn’t have any return type, not even void.
• A class can have any number of constructors.
• Access modifiers can be used in constructor declaration to
control its access
• i.e. which other class can call the constructor.
Constructors in C#
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance
Single Inheritance
• In this type of inheritance, a derived class inherits from a base class, and at the
same time, the derived class itself also acts as a base class for some other class.
using System;
class Son : Father
class GrandFather
{
{
public void written()
public void write()
{ Console.WriteLine("Son");
{ }}
Console.WriteLine("GrandFather"); class Example
}} {
class Father : GrandFather static void Main(string[] args)
{ {
public void wrote() Son s = new Son();
{ s.write();
Console.WriteLine("Father"); s.wrote();
}} s.written();
}}
Hierarchical Inheritance
• Array initialization in C#
• In C#, we can initialize an array during the declaration.
• For example, int [] numbers = {1, 2, 3, 4, 5};
• We can access the elements in the array using the index of the array.
• In C#, we can use loops to iterate through each element of an array.
using System;
namespace AccessArrayFor
{
class Program {
static void Main(string[] args) {
int[] numbers = { 1, 2, 3};
for(int i=0; i < numbers.Length; i++) {
Console.WriteLine("Element in index " + i + ": " + numbers[i]);
}
}
}
}
Using foreach loop
using System;
namespace AccessArrayForeach {
class Program
{
static void Main(string[] args)
{
int[] numbers = {1, 2, 3};
Console.WriteLine("Array Elements: ");
foreach(int num in numbers)
{
Console.WriteLine(num);
}
}}}
Advantages of C# Array
• Code Optimization (less code)
• Random Access
• Easy to traverse data
• Easy to manipulate data
• Easy to sort data etc.
//traversing array
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
C# Multidimensional Array
• The multidimensional array is also known as rectangular arrays in C#.
• It can be two dimensional or three dimensional.
• The data is stored in tabular form (row * column) which is also known
as matrix.
• To create multidimensional array, we need to use comma inside the
square brackets.
• For example:
int[ ][ ] jaggedArray = {
• new int[ ] {10, 20, 30},
• new int[ ] {11, 22},
• new int[ ] {88, 99}
• };
Accessing elements of a jagged array:
• We can access the elements of the jagged array using the index number. For
example,
• // access first element of second array
• jaggedArray[1][0];
• In C#, we have the System.Linq namespace that provides different methods to perform various
operations in an array.
using System;
using System.Linq; // provides us various methods to use in an array
namespace ArrayMinMax {
class Program {
static void Main(string[] args) {
int[] numbers = {51, 1, 3, 4, 98};
// get the minimum element
Console.WriteLine("Smallest Element: " + numbers.Min());
// Max() returns the largest number in array
Console.WriteLine("Largest Element: " + numbers.Max());
Console.WriteLine("Sum is: " + numbers.Sum());
Console.WriteLine( "Average is: " +numbers.Average());
} }}
• The System.Array class also includes methods for creating, manipulating, searching, and
sorting arrays. See list of all Array methods
using System;
public class Program
{
public static void Main(){
int[] nums = { 10, 15, 16, 8, 6 };
Console.WriteLine("Original Array");
foreach(var element in nums)
Console.WriteLine(element);
Array.Sort(nums);
Console.WriteLine("Sorted Array");
foreach(var element in nums)
Console.WriteLine(element);
Array.Reverse(nums);
Console.WriteLine("Reversed Array");
Array.ForEach<int>(nums, n => Console.WriteLine(n));
Console.WriteLine(Array.BinarySearch(nums, 15));
}}
C# Tuples
• A tuple in C# allows us to store elements of different data types.
For example,
• var student = ("Taylor", 27, "Orlando");
• Create Tuple in C#:
• C# provides various ways for creating tuples.
1. Using Parentheses
2. Using the Create() Function
1. C# Tuple Using Parentheses
• We can create a tuple by directly assigning different values using parentheses ().
using System;
class Program {
public static void Main() {
// create a tuple containing 3 elements
var student= ("Taylor", 5, "Orlando");
Console.WriteLine(student);
}
}
• In this way, we can store data elements of different data types inside a tuple
without mentioning the datatype.
using System;
class Program {
public static void Main() {
(string,int,string) student = ("Taylor", 5, "Orlando");
Console.WriteLine(student);
}
}
// Output: (Taylor, 5, Orlando)
2. C# Tuple using Create() Method
• Create() method to create a tuple without having to mention the
datatypes of the tuple elements.
• The syntax for creating tuple using Create() is:
• var t1 = Tuple.Create(value);
using System;
class Program
{
public static void Main() {
// create a tuple containing 3 elements
var programming = Tuple.Create("programiz", "java", 12);
Console.WriteLine(programming);
}
}
Note: While creating a tuple using the Create() method it can only include a
maximum of eight elements.
Access Tuple Elements
using System;
class Program {
public static void Main() {
var roll_num = (5, 7, 8, 3);
// original tuple
Console.WriteLine("Original Tuple: " + roll_num);
// replacing the value 7 with 6
roll_num.Item2 = 6;
Console.WriteLine("Changing value of 2nd element to " + roll_num.Item2);
Console.WriteLine("Modified Tuple: " + roll_num);
}}
• Note: If we have used Create() to create a tuple, then we
cannot change the value of the elements. That means the
elements of the tuple are read-only.
using System;
class Program {
public static void Main() {
var t1= Tuple.Create("Taylor", "Jack");
t1.Item2 = "Monica";
Console.WriteLine(t1.Item2);
}
}
Delegate
• Any method which has the same signature as delegate can be assigned
to delegate.
• in C#, delegate is a reference to the method.
• It is very similar to the function pointer but with a difference that
delegates are a type-safe.
• In other words, delegates are used to pass methods as arguments to
other methods
• There are three steps for defining and using delegates:
• Declaration
• A delegate is declared by using the keyword delegate, otherwise it
resembles a method declaration.
• Instantiation
• To create a delegate instance, we need to assign a method (which has
same signature as delegate) to delegate.
• Invocation
• Invoking a delegate is like as invoking a regular method.
Types of delegates
1) Singlecast delegates
Singlecast delegate point to single method at a time.
2) Multiplecast delegates
In C#, delegates are multicast, which means that they can point to
more than one function at a time.
using System;
public static void Main()
{
namespace DemoDelagates Example obj = new Example();
{
MyDelagate delob = new
public delegate int MyDelagate(int a, int b); MyDelagate(obj.Sum);
}}}
Console.WriteLine("addition ="+(x + y));
}
public void subtract_Method(int x, int y) Out put :
{ addition =60
subtraction=40
Console.WriteLine("subtraction="+(x - y));
}
Multicast example
Generic Features
• Generic means the general form, not specific. In C#, generic means
not specific to a particular data type.
• Generic is a concept that allows us to define classes and methods with
placeholder.
• C# compiler replaces these placeholders with specified type at compile
time. The concept of generics is used to create general purpose classes
and methods.
• A generic type is declared by specifying a type parameter in an angle
brackets after a type name, e.g. TypeName<T> where T is a type
parameter.
• It helps you to maximize code reuse, type safety, and performance.
• You can create generic collection classes. The .NET Framework class
library contains several new generic collection classes in the
System.Collections.Generic namespace.
• You can create your own generic interfaces, classes, methods, events,
and delegates.
• You may create generic classes constrained to enable access to
methods on particular data types.
Generic Class
{
Console.WriteLine(msg);
}
}