0% found this document useful (0 votes)
58 views

Module 4

This document provides information about properties in C# and different collection classes like ArrayList, Hashtable, and SortedList. It discusses encapsulation in C# and how properties provide a way to access private fields through accessor methods while looking like fields. It also summarizes key properties and methods of common collection classes and how they organize and access elements differently based on properties like being sorted, allowing duplicates, or using a key to access values.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Module 4

This document provides information about properties in C# and different collection classes like ArrayList, Hashtable, and SortedList. It discusses encapsulation in C# and how properties provide a way to access private fields through accessor methods while looking like fields. It also summarizes key properties and methods of common collection classes and how they organize and access elements differently based on properties like being sorted, allowing duplicates, or using a key to access values.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 45

Department of Information

Science

17IS564:C#.Net

Module-4: Defining Extensible Types


with C#
Chapter 15:Implementing properties to
access fields

What is Encapsulation?
• Encapsulation enables the language’s ability to hide
unnecessary implementation details from the object user.
• The concept of encapsulation revolves around the notion
that an object’s field data should not be directly accessible
from the public interface. 
• In C#, encapsulation is enforced at the syntactic level
using the public, private, protected, and protected internal
keywords.
• // A class with a single public field. public class Book
{
public int numberOfPages;
}
static void Main(string[] args)
 {
 Book miniNovel = new Book();
 miniNovel.numberOfPages = 30000000;
 
}
Enforcing Encapsulation Using
Traditional Accessors and Mutators
• If we want to access any private data, we
can write a traditional accessor (get
method)
• When we want to provide value to data,
we can write a mutator (set method). For
example,
// Traditional accessor and mutator for a point of private data. public class
Employee
{
private string fullName;
//Accessor.
public string GetFullName()
{
return fullName;
 
}
 
// Mutator.
 
public void SetFullName(string n)
 {
fullName = n;
 
}
 }
// static void Main(string[] args)
 {
 
Employee p = new Employee();
p.SetFullName("Fred Flintstone");
onsole.WriteLine("Employee is named: {0}", p.GetFullName());
Console.ReadLine();
Another Form of Encapsulation:
Class Properties
• A property is a cross between a field and a
method—it looks like a field but acts like a
method.
• · You access a property by using exactly the
same syntax that you use to access a field. 
• However, the compiler automatically translates
this field-like syntax into calls to accessor
methods (sometimes referred to as property
getters and property setters).
The syntax for a property
declaration looks like this:
<AccessSpecifier> <return_Type> <PropertyName>
{
get
{
// read accessor code
}
set
{
 // write accessor code
}
}
•A property can contain two blocks of code, starting with the get and set keywords.
•The get block contains statements that execute when the property is read, and the set
block contains statements that run upon writing to the property
Auto Implemented Property
Static Property
Abstract Property
Interface Properties

public interface ISample


{
// Property declaration:
string Name
{
get;
set;
}
}
INDEXER
Declaration of Indexer
Multidimensional Indexers
• The multi-dimensional indexer is almost similar to 
multidimensional arrays. For the efficient content-
based retrieval of data, multidimensional indexers
are used. To create multi-dimensional indexer you
have to pass at least two parameters in the
argument list of indexer declaration. To access a
single element of a multi-dimensional indexer, use
integer subscripts. Each subscript indexes a
dimension like the first indexes the row dimension,
the second indexes the column dimension
Generics
Generics. Generic classes have type parameters.
Separate classes, each with a different field type
in them, can be replaced with a single generic
class.
A generic class introduces a type parameter
(often specified as the letter T). This becomes
part of the class definition itself. Generic
methods can also be designed.
• Why the name Generic?
– We separate the behavior from the type
allowing more generic behavior
descriptions.
• Also called Parametric Polymorphism
– We supply a type parameter and the same
code or behavior applies to this type.
Generic Parameterization
• Generics can be used with:
– Types
• Struct
• Interface
• Class
• Delegate
– Methods
Syntax
<access_specifier> Class <class Name> (<T>)
{

}
Class program <T>
{

}
class MyGenericClass<T>
{
private T genericMemberVariable;
public MyGenericClass(T value)
{
genericMemberVariable = value;
}
public T genericMethod(T genericParameter)
{
Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
return genericMemberVariable;
}
public T genericProperty
{
get; set;
}
}
The following figure illustrates how the compiler will replace T with int in
MyGenericClass.
class CompareClass
 {  
    public bool Compare(string x, string y) {  
        if (x.Equals(y)) return true;  
        else return false;  
    }  
    public bool Compare(int x, int y) {  
        if (x.Equals(y)) return true;  
        else return false;  
    }  
}  
Generic method 
• Generic methods have type parameters. They
provide a way to parameterize the types used in
a method. One implementation is used with
many different types.
Note: The syntax form for the declaration uses the
<T> characters after the method name but
before the formal parameter list.
System.Collections
• Collection classes are specialized classes for data
storage and retrieval. These classes provide support
for stacks, queues, lists, and hash tables. Most
collection classes implement the same interfaces.
• Collection classes serve various purposes, such as
allocating memory dynamically to elements and
accessing a list of items on the basis of an index etc
• These classes create collections of objects of the
Object class, which is the base class for all data
types in C#.
ArrayList class
• It represents an ordered collection of an
object that can be indexed individually. It is
basically an alternative to an array.
• However unlike array you can add and
remove items from a list at a specified
position using an index and the array resizes
itself automatically.
• It also allow dynamic memory allocation,
adding, searching and sorting items in the list.
Proper Description
ty
Capacity Gets or sets the number of elements that the ArrayList can contain.
Count Gets the number of elements actually contained in the ArrayList.
IsFixedSi Gets a value indicating whether the ArrayList has a fixed size.
ze
Item Gets or sets the element at the specified index.

1 public virtual int Add( object value ); Adds an object to the end of
the ArrayList.
2 public virtual void AddRange( ICollection c );
Adds the elements of an ICollection to the end of the ArrayList.
3 public virtual void Clear();Removes all elements from the
ArrayList.
4 public virtual bool Contains( object item );
Determines whether an element is in the ArrayList.
5 public virtual void Insert( int index, object value );
Inserts an element into the ArrayList at the specified index.
6 public virtual void Remove( object obj );
Removes the first occurrence of a specific object from the
ArrayList.
7 public virtual void RemoveAt( int index );
Removes the element at the specified index of the ArrayList.
8 public virtual void Reverse();
Hashtable class
• The Hashtable class represents a collection of
key-and-value pairs that are organized based
on the hash code of the key. It uses the key to
access the elements in the collection.
• A hash table is used when you need to access
elements by using key, and you can identify a
useful key value. Each item in the hash table
has a key/value pair. The key is used to
access the items in the collection
Proper Description
ty
Count Gets the number of key-and-value pairs contained in the Hashtable.
IsFixedS Gets a value indicating whether the Hashtable has a fixed size.
ize

Item Gets or sets the value associated with the specified key.
Keys Gets an ICollection containing the keys in the Hashtable.
Values Gets an ICollection containing the values in the Hashtable.
Methods
1 public virtual void Add( object key, object value );
Adds an element with the specified key and value into the Hashtable.

2 public virtual void Clear();


Removes all elements from the Hashtable.

3 public virtual bool ContainsKey( object key );


Determines whether the Hashtable contains a specific key.

4 public virtual bool ContainsValue( object value );


Determines whether the Hashtable contains a specific value.

5 public virtual void Remove( object key );


Removes the element with the specified key from the Hashtable.
SortedList class
• The SortedList class represents a collection of
key-and-value pairs that are sorted by the keys
and are accessible by key and by index.
• A sorted list is a combination of an array and a
hash table. It contains a list of items that can be
accessed using a key or an index. If you access
items using an index, it is an ArrayList, and if
you access items using a key, it is a Hashtable.
The collection of items is always sorted by the
key value.
Proper Description
ty
Capacity Gets or sets the capacity of the SortedList.
Count Gets the number of elements contained in the SortedList.
IsFixedSize Gets a value indicating whether the SortedList has a fixed size.

Item Gets and sets the value associated with a specific key in the SortedList.
Keys Gets the keys in the SortedList.
Values Gets the values in the SortedList.

S.N Method Name & Purpose


1 public virtual void Add( object key, object value ); Adds an element with the
specified key and value into the SortedList.
2 public virtual void Clear(); Removes all elements from the SortedList.
3 public virtual bool ContainsKey( object key ); Determines whether the
SortedList contains a specific key.
4 public virtual bool ContainsValue( object value ); Determines whether the
SortedList contains a specific value.

5 public virtual object GetKey( int index ); Gets the key at the specified index of
the SortedList.
6 public virtual int IndexOfKey( object key ); Returns the zero-based index of the
specified key in the SortedList.
7 public virtual int IndexOfValue( object value ); Returns the zero-based index of
the first occurrence of the specified value in the SortedList.
8 public virtual void Remove( object key ); Removes the element with the
specified key from the SortedList.
Stack class
• It represents a last-in, first out collection of
object. It is used when you need a last-in, first-
out access of items. When you add an item in
the list, it is called pushing the item and when
you remove it, it is called popping the item.
Property Description
Count Gets the number of elements contained in the Stack.

S.N Method Name & Purpose


1 public virtual void Clear();
Removes all elements from the Stack.
2 public virtual bool Contains( object obj );
Determines whether an element is in the Stack.
3 public virtual object Peek();
Returns the object at the top of the Stack without removing it.

4 public virtual object Pop();


Removes and returns the object at the top of the Stack.

5 public virtual void Push( object obj );


Inserts an object at the top of the Stack.
6 public virtual object[] ToArray();
Copies the Stack to a new array.
Queue class
• It represents a first-in, first out collection of
object. It is used when you need a first-in,
first-out access of items. When you add an
item in the list, it is called enqueue, and
when you remove an item, it is called
deque.
Property Description
Count Gets the number of elements contained in the Queue.

S.N Method Name & Purpose


1 public virtual void Clear();
Removes all elements from the Queue.
2 public virtual bool Contains( object obj );
Determines whether an element is in the Queue.
3 public virtual object Dequeue();
Removes and returns the object at the beginning of the Queue.

4 public virtual void Enqueue( object obj );


Adds an object to the end of the Queue.
5 public virtual object[] ToArray();
Copies the Queue to a new array.
6 public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the Queue.

You might also like