Category Archives: C# Tutorial

C# Generic Stack<T> Tutorial with Programming Example

In this chapter you will learn

  • What is Generic Stack<T> in C#?
  • How to Initialize Generic Stack<T> in C#?
  • Programming Example

What is Generic Stack<T> in C#?

Stack is based on Last In First Out [LIFO] mechanism. It is required when you need to access recently added item first. For example, all of you would have used Undo function. When you press Ctrl + Z then the last changes made by you reversed. It is an example of stack.

How to initialize Stack<T>?

Important Properties and Methods of Stack

PropertiesDescription
CountReturns the total count of elements in the Stack.
MethodsDescription
PushInserts an item at the top of the stack.
PeekReturns the top item from the stack.
PopRemoves and returns items from the top of the stack.
ContainsChecks whether an item exists in the stack or not.
ClearRemoves all items from the stack.

Programming Example

Output

Saturday | Friday | Thursday | Wednesday | Tuesday | Monday | Sunday |
Top Item is : Saturday
Removed Top Item of Stack : Saturday
Now Stack’s Items are :
Friday | Thursday | Wednesday | Tuesday | Monday | Sunday |

_

Summary

In this tutorial you learned about Generic Stack&<T> In C# with programming example.


C# Generic Queue<T> Tutorial with Programming Example

In this chapter you will learn:

  1. What is Queue<T> in C#?
  2. How to initialize it?
  3. Understand C# Queue with Programming Example

What is Queue<T>?

Queue Represents First In – First Out collection of objects. Let’s understand it with easy example. Take an example of line of ticket counter. The person which comes first take ticket first. All the person wait according to their insertion order in line and when they reach top of the line they get ticket. In C# programming, Queue<T> does the same thing. The item which is inserted first can be accessed first.


How to Initialize a Queue?

You can initialize queue as follows:

Properties

PropertiesDescription
CountGets the number of elements contained in the Queue<T>.

Methods

MethodsDescription
Clear()Removes all objects from the Queue<T>.
Contains(T)Determines whether an element is in the Queue<T>.
CopyTo(T[], Int32)Copies the Queue<T> elements to an existing one-dimensional Array, starting at the specified array index.
Dequeue()Removes and returns the object at the beginning of the Queue<T>.
Enqueue(T)Adds an object to the end of the Queue<T>.
Equals(Object)Determines whether the specified object is equal to the current object.(Inherited from Object.)
Finalize()Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)
GetEnumerator()Returns an enumerator that iterates through the Queue<T>.
GetHashCode()Serves as the default hash function. (Inherited from Object.)
GetType()Gets the Type of the current instance.(Inherited from Object.)
MemberwiseClone()Creates a shallow copy of the current Object.(Inherited from Object.)
Peek()Returns the object at the beginning of the Queue<T> without removing it.
ToArray()Copies the Queue<T> elements to a new array.
ToString()Returns a string that represents the current object.(Inherited from Object.)
TrimExcess()Sets the capacity to the actual number of elements in the Queue<T>, if that number is less than 90 percent of current capacity.

Programming Example

Output

Mark | Jack | Sarah | Smith | Robbie |
Removing Mark from List.
New list is :
Jack | Sarah | Smith | Robbie |
Printing City List
Newyork | California | Las Vegas | Count3
_

Summary

In this chapter you learned Queue<T> in C# with complete programming example. In the next chapter you will learn Stack<T> in C# Generics.


C# Generic SortedList with Programming Example

In this chapter you will learn

  • What is Generic SortedList<TKey,Tvalue> Programming in c#?
  • How to write program using Sorted List in C#?

C# Generic SortedList represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation. It belongs to System.Collections.Generic namespace. It is similar to SortedDictionary but still there are some differences between them like

  1. SortedList uses less memory than SortedDictionary
  2. SortedDictionary has faster insertion and removal operations for unsorted data than SortedList
  3. If the list is populated all at once from sorted data then SortedList works faster than SortedDictionary.
  4. SortedList supports efficient indexed retrieval of keys and values.

SortedList doesn’t allow inserting null value and duplicate value. Every key in a SortedList must be unique otherwise it throws ArgumentException.

Initialization

Important Properties and Methods of SortedList<TKey, TValue>

PropertiesDescription
CapacityGets or sets the number of elements that the SortedList<TKey,TValue> can store.
CountGets the total number of elements exists in the SortedList<TKey,TValue>.
IsReadOnlyReturns a boolean indicating whether the SortedList<TKey,TValue> is read-only.
ItemGets or sets the element with the specified key in the SortedList<TKey,TValue>.
KeysGet list of keys of SortedList<TKey,TValue>.
ValuesGet list of values in SortedList<TKey,Tvalue>.

Important Methods

MethodsDescription
void Add(TKey key, TValue value)Add key-value pairs into SortedList<TKey, TValue>.
void Remove(TKey key)Removes element with the specified key.
void RemoveAt(int index)Removes element at the specified index.
bool ContainsKey(TKey key)Checks whether the specified key exists in SortedList<TKey, TValue>.
bool ContainsValue(TValue value)Checks whether the specified key exists in SortedList<TKey, TValue>.
void Clear()Removes all the elements from SortedList<TKey, TValue>.
int IndexOfKey(TKey key)Returns an index of specified key stored in internal array of SortedList<TKey, TValue>.
int IndexOfValue(TValue value)Returns an index of specified value stored in internal array of SortedList<TKey, TValue>
bool TryGetValue(TKey key, out TValue value)Returns true and assigns the value with specified key, if key does not exists then return false.

Programming Example

Output

Keys : 1 Values : Jack
Keys : 2 Values : Mark
Keys : 3 Values : Neo
Keys : 4 Values : Steven
Keys : 5 Values : Clark

This key already exist. System.ArgumentException: An item with the same key has already been added. Key: 5
Parameter name: key
at System.Collections.Generic.SortedList`2.Add(TKey key, TValue value)
at SortedList_Example.Program.Main(String[] args) in /home/prashant/Documents/SEODocuments/CONTENT/Program/CSharp/GenericSortedList/Program.cs:line 27

Items Found at Position : 3

Key : 1 – Value : James Smith
Key : 2 – Value : Mark
Key : 3 – Value : Neo
Key : 4 – Value : Steven
Key : 5 – Value : Clark
Length of StudentList is 5
_

Summary

In this chapter you learned Generic SortedList with complete programming example. In the next chapter you will learn Hashset<T> in C#.


C# Generic Dictionary Tutorial with Example

In this chapter you will learn

  1. What are Generic Dictionary Class?
  2. How to declare it?
  3. Programming Example

What are Generics Dictionary Class?

Dictionary is a collection of keys and Values. We bind values with keys and store them in dictionary and later that key is used for accessing dictionary value. Generic Dictionary is type safe and avoid boxing and unboxing and provides complete benefit of Dictionary. Generic Dictionary belongs to System.Collection.Generic namespace.

Generic Collection doesn’t allow inserting duplicate keys.

Important Methods of Generic Dictionary Class

Properties

PropertiesUsage
ComparerGets the IEqualityComparer that is used to determine equality of keys for the dictionary.
CountGets the number of key/value pairs contained in the Dictionary.
Item[TKey]Gets or sets the value associated with the specified key.
KeysGets a collection containing the keys in the Dictionary.
ValuesGets a collection containing the values in the Dictionary.

Methods

MethodsUsage
Add(TKey, TValue)Adds the specified key and value to the dictionary.
Clear()Removes all keys and values from the Dictionary.
ContainsKey(TKey)Determines whether the Dictionary contains the specified key.
ContainsValue(TValue)Determines whether the Dictionary contains a specific value.
Equals(Object)Determines whether the specified object is equal to the current object.(Inherited from Object.)
Finalize()Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)
GetEnumerator() Returns an enumerator that iterates through the Dictionary.
GetHashCode()Serves as the default hash function. (Inherited from Object.)
GetObjectData(SerializationInfo, StreamingContext)Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the Dictionary instance.
GetType()Gets the Type of the current instance.(Inherited from Object.)
MemberwiseClone()Creates a shallow copy of the current Object.(Inherited from Object.)
OnDeserialization(Object)Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete.
Remove(TKey)Removes the value with the specified key from the Dictionary.
ToString()Returns a string that represents the current object.(Inherited from Object.)
TryGetValue(TKey, TValue)Gets the value associated with the specified key.

Programming Example

Output

Star Wars
[sci-fi, Star Wars]
[Action, The One]
[Fantacy, Star Dust]
[Computer, Algorithm]
[Love, 50 First Dates]
Key found. Value is Star Wars
_

Summary

In this chapter you learned Generic Dictionary class with complete programming example. In the next chapter you will learn Generic SortedList.


C# Generic Lists with Complete Programming Example

In this chapter you will learn

  1. What are Generic Lists?
  2. How it is different from Collection List
  3. Programming Example

What are Generic Lists

The Generic Lists are similar to arrays. You can add, delete, populate, sort Generic Lists. is a placeholder for data types and replaced by datatype at compile time.

How it is different from Collection Lists?

However, function of the both lists are same but Generic Lists are Type Safe because it is strongly bound by data type. Unlike Collection lists you don’t need to boxing and unboxing Generic Lists.

How to declare Generic Lists

You can declare Generic Lists in following manner:

List intList = new List();

Important Function of Lists

PropertyUsage
ItemsGets or sets the element at the specified index
CountReturns the total number of elements exists in the List
MethodUsage
AddAdds an element at the end of a List.
AddRangeAdds elements of the specified collection at the end of a List.
BinarySearchSearch the element and returns an index of the element.
ClearRemoves all the elements from a List.
ContainsChecks whether the speciied element exists or not in a List.
FindFinds the first element based on the specified predicate function.
ForeachIterates through a List.
InsertInserts an element at the specified index in a List.
InsertRangeInserts elements of another collection at the specified index.
RemoveRemoves the first occurence of the specified element.
RemoveAtRemoves the element at the specified index.
RemoveRangeRemoves all the elements that match with the supplied predicate function.
SortSorts all the elements.
TrimExcessSets the capacity to the actual number of elements.
TrueForAllDetermines whether every element in the List matches the conditions defined by the specified predicate.

Programming Example

Output

Steven Clark Jack
After Sorting
Clark Jack Steven
Removing Clark
Jack Steven
Inserting Mathew at index position 2
Jack Steven Mathew
_

Summary

In this chapter you learned Generic Lists with complete and easy programming example. In the next chapter you will learn Generic Dictionary class with complete programming example.


C# Generics Programming

In this chapter you will learn

  • What are Generics
  • How to Write Generics Program in C#
  • Benefit of Generics in C#

What are Generics

In simple words, Generics are the that type of classes which has PalceHolder instead of datatypes. When you create generic classes you don’t specify its data type; datatypes are defined when you create objects. This makes Generic classes reusable and type-safe and your Generic classes and methods are able work with any datatypes.

More about Generics

  1. Generics improves code usability, type safety and performance.
  2. Mostly Generics are used for creating collection classes.
  3. You can use Generics by adding System.Collections.Generic namespace.
  4. You can create your own Generic interfaces, classes, methods, events and delegates.

Declare Generics Class

Use Generics in Programming

Programming Example

Output

Printing Integer Value
144
Printing String Value
Hello String
_

Here, I have wrote the very simple program and hope you will understand it very easily. In the above program I have created a Generic class GenClass which has a placeholder. This class also has a method GetFunction that accepts a T type parameter and prints on the console. is a placeholder that is replaced by datatype when created objects.

Summary

In this chapter you learned What are Generics in C# Programming, Its benefit and complete programming exmaple.


C# Polymorphism Practice Question

practicenote-01

Qu 1. Write a program of function overloading that has a function Convert() that accepts a value in parameter and convert them into string and print on screen.
Hint: Convert(int num);
Convert(Double num);
Convert(Fload num);
Qu 2. Write a program using Virtual and Override keyword that does the following tasks.

  1. A virtual function Engine() that has basic properties of engine like Power of engine, RPM, no of Cylinder etc.
  2. This function should be overridden in child class according to function.

Programming Example of C# Polymorphism

example

Qu 1. Write a program to save data to database. There should be a function Save() that accepts one, two or three values as parameter and then save that to database.
Answer

Output

No Data to Saved
Jack saved
Jack and 22 are saved on 19-11-2016
_
Qu 2: Write a program using virtual and override keyword in which base class should have a function TyreSize() that should be implemented in derived class using override keyword.
Answer

Output

Default Tyre Size is 13 Inches
Tyre Size is Overriden and new Tyre Size is : 14 Inches
_

Summary

In this chapter you learned Polymorphism using some programming example. In the next chapter there are some programming questions. You must solve that question using programming techniques.


Dynamic Polymorphism in C# with Programming Example

dynamic_polymorphism
In this chapter you will learn:

  • What is Runtime Polymorphism?
  • How to implement it in program?

What is Runtime Polymorphism?

Runtime Polymorphism is also known as Dynamic Polymorphism, Late Binding, Method overriding etc. Whereas in static polymorphism we overload a function; in dynamic polymorphism we override a base class function using virtual or override keyword. Method overriding means having two or more methods with the same name, same signature but with different implementation.

Programming Example

Output

Class : Icecream
Class : Chocolate
IceCream Type : Chocolate
_

GuideLine:

  1. If base class function is marked as virtual then it is compulsory to add override keyword in derived class function.
  2. Virtual method allows child class to their own implementation of derived methods.
  3. Virtual method cannot be declared as private.

You can also learn more about virtual method and override keyword here:

http://www.completecsharptutorial.com/basic/c-abstract-and-virtual-method-inheritance-tutorial-with-code/

Summary

In this chapter you learned Runtime Polymorphism implementation using Virtual and Override keyword. In the next chapter some programming examples are there that will help you to understand polymorphism clearly.


Function Overloading Tutorial C# with Programming Example

function-overloading
In this chapter you will learn:

  • What is Function Overloading?
  • Function Overloading with Programming Example

Function Overloading

In function overloading, a function works differently based on parameters. A single function can have different nature based on number of parameters and types of parameters. For example, you have a function Sum() that accepts values as parameter and print their addition. You can write multiple function with name Sum() but the parameter signature must be different.

Programming Example

Output

No Value Provided
Sum of 5 and 4 is 9
Sum of 9.3 and 8.6 is 17.9
Hello World – is not a numeric value
_

Guidelines

When you are doing method overloading, must remember following guidelines:

  1. Methods must be different based on their signature like number of parameters and types of parameters.
  2. There is no limit for method overloading. You can write multiple methods with same name but the signature must be different.

Summary

In this chapter you learned about Function Overloading in C#. In the next chapter you will learn about Operator Overloading in C# with programming example.