C# Bit Array

c# .net bitArray, examples definition, logic gates.

Advertisements

This is the last post of .Net collections series. You can find my last post about queues here.

Manages a compact array of bit values, which are represented as booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). Like in any other array you can access it items by index value.

BitArray implements interfaces like: ICollection, IEnumerable, ICloneable. Which I’ll cover in my next articles.

public sealed class BitArray : ICollection, IEnumerable, ICloneable

 

This collection can be initialized with one of six constructors. The simplest one takes an integer and initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

BitArray array = newBitArray(16);

Now we can add items to array by selecting index or using Set() method;

        array[3] = true;     // You can set the bits with the indexer.

	array.Set(10, true); // You can set the bits with Set.

 

We can use count property to get number of items in array, or we can use Program class method to count all true values

CountBitArray(array); //Returns bits set to 1

 

Most unique function of this this class is providing methods like And(), Or(), Xor(), this allows to perform operations of logic gates.

public BitArray And(BitArray value);

For example And() method Performs the bitwise AND operation on the elements in the current BitArray against the corresponding elements in the specified BitArray.

static void Main()
 {
     BitArray b1 = new BitArray(4);
     b1.Set(0, true);
     b1.Set(1, true);
     b1.Set(2, false);
     b1.Set(2, false);

     BitArray b2 = new BitArray(4);
     b2.Set(0, true);
     b2.Set(0, false);
     b2.Set(0, false);
     b2.Set(0, true);


     BitArray results = new BitArray(4);


     
    results = b1.And(b2);
     foreach(bool value in results)
     {
     Console.WriteLine(value);
     }
     Console.ReadLine();
 }

This simple example returns:

  • True
  • False
  • False
  • False

 

BitArray is an intresting type of collection, it’s not very popular it i can be useful even if the performance isn’t the best. It allows to perform operations like crating logic gates, what can be used to create more complex things like flip-flop, and modulo counters.

This was probably the last entry about .NET collections next article will be about Unity Engine. Stay Awesome!

C# Queue

c# queue explained, definition, examples.

In my last post you can find explanation of Stack Collection. Concept of both collections is similar.

Queue is a FIFO(first-in, first out) collection of objects. It’s generic type that is part of  System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class:Enqueue(Object),Dequeue(),Peek(). First lets explain the FIFO concept.

queue-line_2991665

 

Queue line can be a good, real world example of FIFO concept. Person who will stand in line first will be served first. Using this concept we can enqueue the items into a queue and get it in the same order. Let’s move on to class syntax.

 

Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.

Queue<int> queue = new Queue<int>();

 

Let’s look at the methods

 Enqueue(Object)

class Program
{
    static void Main()
    {
	Queue<int> queue = new Queue<int>();
	queue.Enqueue(1);
	queue.Enqueue(2);
	queue.Enqueue(3);
	queue.Enqueue(4);
}
}

We crate new queue and by using Enqueue() method  we add new items to the collection.  Simple as that

Dequeue()

Removes the object at the beginning of your Queue. The algorithmic complexity of this is O(1). It doesn’t loop over elements.

queue.Dequeue();

this method doesn’t take any parameters

Peek()

This method works the same way as in stack. It returns the value without removing it. In this case first value in queue.

queue.Peek();

 

This is not the most popular type of collections, but it can be useful for creating things like for example, player turn system in strategy game. In next post I’ll cover another type of collection, bitArray. Stay Awesome!

 

C# Stack

stack collection in c#

Stack is a LIFO(last-in, first out) collection of objects. It’s generic type that is part of  System.Collections.Generic. You can read more about generics in my last post. There are three most important methods in this class: Peek(),Pop(),Push(). First lets explain the LIFO concept.

1872-plates-pile

 

Great example of LIFO visualization is a stack of plates. When new plate is added its stored on the top of the stack, and when we want to remove a plate we can only grab the top one. Same idea is used in programming. Using this concept we can push the items into a stack and get it in reverse order. Stack returns the last item first. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.Now lets see the class syntax and implementations of the methods.

Class signature is similar to other generic collections. You can find more about them here. We need to specify the type of the variable that will be stored in the collection.

 Stack<string> numbers = new Stack<string>();

Let’s look at the methods

Push()

First we need to add items to our stack, to do this we will use Push() method

class Program
{
    static void Main()
    {
	Stack<int> stack = new Stack<int>();
	stack.Push(1);
	stack.Push(2);
	stack.Push(3);

	foreach (int i in stack)
	{
	    Console.WriteLine(i);
	}
    }
}

Output:

3

2

1

 

Push method adds elements to he top of the stack, elements are printed in reverse order.

Pop() and Peek()

when we have elements in our stack we can now return them with Pop() method, this will delete item from stack. If we want to copy the value, leaving it on the top of the stack we use Peek() method.

static void Main()
    {
	int pop = stack.Pop();
	Console.WriteLine(pop);

	int peek = stack.Peek();
	Console.WriteLine("Element at the top:");
	Console.WriteLine(peek);
    }

Output:

3

Element at the top:2

Now you can add and remove items from stack.  Stack can be useful for simulating for example deck of cards. In next article I’ll cover similar type called queue. Stay Awesome!

C# Dictionary

dictionary in c# .net

In last post about hashtables, I mentioned that there is more efficient type of hashtable called dictionary. I recommend you to read that article before moving to dictionaries. Dictionary is part of System.Generic. Concept of dictionary is the same as Hashtable , A It is a data structure that represents a collection of keys and values pair of data. In dictionaries we need to define the type of variable that will be stored in collection. This makes no need for boxing/unboxing process, what effects the collection performance. Dictionary is part of generic collection what means we can use it with any data types

Lest take a look at example of Dictionary.

class Program
{
    static void Main()
    {
	Dictionary<string, int> dictionary = new Dictionary<string, int>();

	dictionary.Add("John", 10);
	dictionary.Add("Bob", 5);
    }
}

Syntax of Dictionary is similar to Generic List, you can read more details about it here.

We can loop through object the same way as we do with hashtables, but in dictionaries we use KeyValuePair structure, it contains key and value of the object

foreach (KeyValuePair<string, int> kvp in dictionary)
	{
	    Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
	}

we can replace

(KeyValuePair<string, int> kvp in dictionary)

with

(var kvp in dictionary)

what makes code easier to read, and reduce the time of typing

 

We can search through collection to find value or key we want. Here is another difference between hashtable and dictionary. Dictionary returns error if we try to find a key which does not exist. While Hashtable returns null.

if (dictionary.ContainsKey("Bob") == true) 
    { 
          Console.Writeline(dictionary["Bob"].ToString ()); 
    } 
else 
    {
          Console.Writeline("Key does not exist"); 
    }

We can perform much more operations on this collection. But I described the most essential  of them. Dictionary is one of the most popular and frequently used collection type. In next post I’ll move to different types of collections like Stack or Queue. Stay Awesome!

 

Hashtable

introduction to hashtable in c# .net

Hashtable is part of System.Collection namespace. You can read more about collections here. The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. A hash table is made up of a mapping function and an array. It uses the key to access the elements in the collection. The mapping function is used to assign numerical values (keys) to the data. This helps in categorizing the data, which speeds up search times when you search for it. Hashtable is an older .NET Framework type. It is slower than the generic Dictionary type. In hashtable we don’t declare type of the object with it signature.

Lest crate an example of hashtable.

 static void Main()
    {
                Hashtable hashtable = new Hashtable();
                hashtable[1] = "John";
                hashtable[4] = "Mike";
                hashtable[7] = "Bob";
    }

We can use class constructor to crate empty table, and than assign values to the selected index.

Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be. DictionaryEntry  defines a dictionary key/value pair that can be set or retrieved. DictionaryEntry have two properties value and key. We can use this structure to loop through all objects in the table.

 foreach (DictionaryEntry entry in hashtable)
        {
              Console.WriteLine("{0} : {1}", entry.Key, entry.Value);
        }

 

We can use conditions to check the data status before performing an action

public virtual bool ContainsKey(object key);

 

Hashtables are much more efficient than most other search trees when it comes to finding data. They are used in all kinds of computer software – especially database software.

We can use method like Add() or Remove() function to manipulate data in easy to understand way.

	hashtable.Add(1, "Sandy");
	hashtable.Add(2, "Bruce");

 

This was just an introduction to the subject, hash table is more complex subject that involves many rules like that the hash function should assign unique keys to each data slot, but in practice a pair of keys might get hashed to the same table. This is called collision. There are two ways of dealing with it. I’ll describe both of them in next post.

 

 

 

Collections

introduction to collections in C# .NET

In last post I wrote about implementation of generics, and the difference between list and an array. Today we will take closer look at Collections. This is more general subject, mentioned earlier generics are part of System.Collection class.

Collections are used to group objects and simplify the process off adding, removing and manipulating data. Collections are a very good alternative of arrays. To see the difference we need to look at the arrays first. Let’s take an example, this array is storing object of simple class called Student.

Here is our Student Class

public class Student
 {
 public int ID { get; set; }
 public string Name { get; set; }
 public string Grade { get; set;}
 }

now we create few instances, like this one

 Student student1 = new Student()
 {
 ID = 123,
 Name = "John",
 Grade = "A"
 };

We will use those data for other examples as well.

Array of objects will look like this

Student[] arrayOfStudents = new Student[3];
 arrayOfStudents[0] = student1;
 arrayOfStudents[1] = student2;
 arrayOfStudents[2] = student3;

now let’s say that we want to ad another student to our class. can we just write

arrayOfStudents[3] = student4;

Answer is, No. Writing this we will not have any syntax errors, but our program will crash. Adding new items is just one example of how not flexible arrays are. Imagine you have to remove item and  than shift all indexes. Here’s  where collections really shine.

Array List

What is an ArrayList? In post about generics we analysed collection List<>. So what’s the difference between generic List<> and ArrayList?

ArrayList is part of System.Collections namespace, while List<> is inherent from System.Collections.Generics. ArrayList was part of earliest version of .NET, and it can store objects of different type like string and integer together.

ArrayList newlist = new ArrayList();
 newlist.Add(10);
 newlist.Add(36);
 newlist.Add("John");

This can cause many problems for example while we iterating through our array and we want to compare the  value with a number.

That’s why with Generic List<> we have declared type of the stored variables while we crating our list.

Basic Collections methods

Lets go back to previous example. This time lets use ArrayList insted

 ArrayList listOfStudents = new ArrayList();
 listOfStudents.Add(student1);
 listOfStudents.Add(student2);
 listOfStudents.Add(student3);

now we can simply add new students, by using Add method

 listOfStudents.Add(student4);

in similar way we can remove the object, by using Remove()

listOfStudents.Remove(student3);

Those are just simplest and most basic methods. List of full documentation you can find here .

One more interesting feature. You can convert Array into ArrayList, and reverse. To convert ListArray into array just use, in this example:

ArrayList newListOfStudents = new ArrayList(arrayOfStudents);
//Print data to make sure it works properly
 Console.WriteLine(newListOfStudents.IndexOf(student3));

In next part we will analyse other types of collections like Hash Tables, Binary Trees or Stacks. And we will see how to use properties of keys. Stay Awesome!

 

Introduction to Generics

Have you ever used List class in your program?  Did you noticed strange <> brackets in the syntax, brackets where you can pass  any type of data? Well, that’s example of practical use of generics.

Generis are used to delay specification of data type, means that allows you to write a class or method that can work with any data type. In this post I’ll be using C#.

Lists

Generics are implemented from System.Collections.Generic” namespace. List is probably the most popular Class that inherits from this namespace.

For people unfamiliar with lists: List  represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists. Lists are similar to arrays, both are created to store data of the same type in one place of memory, where we can add new item or find item by index. but have a lot of That’s enough of theory lets take a look at examples:

class Program  
{
    static void Main() 
{
	List<int> list = new List<int>();   //Creating our list
	list.Add(2);                         // Adding new items
	list.Add(3);
	list.Add(5);
	list.Add(7);
    }
}

In this example we create a simple list of integers. Lists comes with a predefined methods such as Add(), Remove(), that makes life a lot of easier, but let’s back to the generics…

List<T>()

<T> represents data type, that means you can create list of integers, characters etc..

Functions

Let’s move on to the functions

 class CreateArrayOfChosenData<T>             // Creating new Class
 {
    private[T] array;

    static CreateArrayOfChosenData(int size//Creating constructor of this class
     {
          array =  new T[size+1];           // Array indexes starts with 0
 }
 }

We are creating simple class that will produce an array of chosen data type and length

CreateArrayOfChosenData<Int> = new CreateArrayOfChosenData<Int>(10);

Here we are creating an instance of our class and passing data type as Int, and  10 as a number of items. Here you can see difference of how each bracket works.

Methods

Generics can also be used in methods. In this simple example we will simply pass values to the method and print the result.

 

class MyClass
 {
     static void CreateAnyTypeofObjects<T,U> (T type1,U type2)
     {
     T object1=type1;
     U object2=type2;
     Console.WriteLine("first object ={0}, secound object ={1}",object1,object2);

    }

We can see that we can create more than one type of object to select, and perform operations on passed objects. This method only illustrates the core structure of creating method with generics fields.

In the next part I’ll try to explain generics in concept of delegates, generic types of return. and functions Func<>,Action<>.