Events

In last post we discussed implementation of Delegates using one simple example. If you haven’t read it already i strongly encourage you to do so before moving to today’s  topic. Today we will take closer look at events. In last example we created one main class with all methods inside it. Today we will learn how to communicate between different classes, by subscribing to the event.

Lets create our first class called publisher, here we will crate our event and we will publish it. This way we will be able to invoke methods in other classes.

using System;

//We are using the delegates we described in last post
public delegate void EventHandler();

class Program
{
 //New event based on the delegate above called newEvent
    public static event EventHandler newEvent;
// Class constructor
public Program(){
//You can put something here
} 
public void AddSubscribers()
    {
	// Add event handlers to our event
	newEvent += new EventHandler(Command1);
	newEvent += new EventHandler(Command2);
	
    }

    static void Command1()
    {
	Console.WriteLine("Event executed");
    }

    static void Command2()
    {
	Console.WriteLine("Warning!");
    }

    public void InvokeEvent(){
    //We are using this to invoke the event
   newEvent.Invoke();
}
}

this is class of our program here we can subscribe new methods to our event and the most important, call our invoke method.

Now lets create second class so we can see how event behave with other classes.

  Public class MainClass{  

public static void Main(){

    Program newProg= new Program();
   //Now we can add our subscribers from Program class
   newProg.AddSubscribers();

    //Or add subscriber from this class
    Subscribe(newProg);

    //Here we finally invoke our event
    newProg.InvokeEent()

    }
    //Here we can subscribe to event of different class
    public Subscribe(Program newProgram){
     newProgram.newEvent += new EventHandler(Command3)
    }
    static void Command3()
    {
        Console.WriteLine("Great!");
    }
}

In this example we can see how we can use event to crate connections between different classes. We can use it in in many different cases, in games development we can crate event calling subscribers when unit is created or destroyed, this way we can easy handle methods spreader between all classes. In next entry I’ll cover lambda expressions, they can help you write more readable code faster. Stay Awesome!

 

 

Delegates

Have  you ever thought about using method as a parameter? Having ability to invoke multiple methods with one command?  Delegates can make those ideas reality .

All delegates are implicitly derived from the System.Delegate class. Here is basic structure of delegates:

delegate <return type> <delegate-name> <parameter list>

Delegate syntax is very similar to the method syntax, i takes list of parameters and have return type. Important thing to consider is that all methods passed to delegate must have the same structure, number and type of parameters and return type. Lets take a look at example:

private delegate int Calculator(int n);
public static int AddNum(int p)

We can see that both methods have the same return types and takes the same parameters.

Let’s move on to the Practical example.

using System;

// Here is our delegate takes int and returns int
private delegate int Calculator(int n);

   class Calculator
   {
      //Initial value
      static int num = 5;

      //Creating methods
      //All methods must have the same structure 
      public static int AddNum(int p)
      {
         num += p;
         return num;
      }
      public static int MultNum(int q)
      {
         num *= q;
         return num;
      }
      public static int SubctNum(int q)
      {
         num -= q;
         return num;
      }
      public static int getNum()
      {
         return num;
      }
      //Calling the main function
      static void Main(string[] args)
      {
         //create delegate instances
         Calculator c1 = new Calculator(AddNum);
         Calculator c2 = new Calculator(MultNum);
         Calculator c3 = new Calculator(SubctNum)

         //We can connect multiple delegates to execute them together 
         c1 += c2;
         c1 += c3;
         
         //We can also delete reference
         c -= c3; 
         
         // Lets call our delegate
         c(2);

         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }

Try this on your compiler see the result.

We just created simple Calculator application that can perform multiple operations with just one call of delegate. This is just the beginning of endless possibilities. Methods can be simplified to shorter versions aka “lambda expressions”.  Try to remember “+=” operator, we will come back to this while we will talk about events, but this is subject for another post. 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<>.

Welcome

First of all, little bit about myself. I’m self taught software developer. My main language is c# and for my projects im using mainly .NET framework and Unity Engine.

Short biography. After doping out from University(Undergraduate in robotics) and over year of searching for place for myself I decided to go back to Software Development. I graduated from college in UK , after seeing the level of education here I decided to become a developer without help of university. I’ll share with you knowledge i gained over years of searching and self development, finishing lots of Massive Open Online Courses, education in different countries and  on different levels.

This blog is about software development and technology. I’ll post helpful tips and information that can be useful for software developers, game developers, and people  interested in technology. I’ll try to cover basic and more advanced topics.