Outrageous C#

Raising the Bar higher with Events, Inheritance, Threading... Try at your own risk.

Posted by Rishi Raj Gujadhur 1/31/2016


Table of content

 

Prerequisites

   
  • Not having Microsoft Visual Studio Ultimate or Express for windows 2012 - 2015

Just kidding, you need to have the above. :)
 

A. Delegates


Delegates allows you to reference and execute several methods at once. (Delegate = Function pointer)

1. Create a new console application.

2. In the program.cs Main method, type:

delegate void myDelegate(string msg);
 
delegate void myDelegate(string message); ----> Declaring a delegate of Name "myDelegate"

Quick tip: the syntax used to declare a delegate is similar to that used to define a method with the delegate keyword in it.

void ----> return type. this delegate will only take methods with the void return type as value. 

delegate ----> keyword used to create a delegate.

(string msg) ----> the delegate will require methods with 1 single string parameter to function.

2. Outside of the Main method, define the following methods:

static void showMsg1(string message)
{

       Console.WriteLine("Hello " + message);
}

static void showMsg2(string message)
{

       Console.WriteLine("Welcome abord the Delegate ship. " + message);
}

3. Inside the Main method, type:

MyDelegate objD = new MyDelegate(showMsg1);
 
MyDelegate objD = new MyDelegate ----> Instantiating the delegate object "objD". Notice that delegates can be instantiated just like classes.

(showMsg1) ----> Initializing the showMsg1 method to the delegate.
 
objD += showMsg2;
 
myFunc += showMsg2; ----> Initialize the method "showMsg2" to the delegate myFunc

 +=  ----> myFunc = myFunc + showMsg2;

objD("Tom");
Console.ReadLine();


Result:

Hello Tom
Welcome aboard the Delegate ship. Tom
 

B. Event


An event is a special type of delegate. You can only add += to an event or remove -= methods from an event. An example of an event is when you left click on your mouse to open Google Chrome (The mouse left_click event). 

1. Create a new console application

2. In program.cs, create a new class "Person".

In class "Person"; type:

class Person
{


public event EventHandler OnPropertyChange;
 
event ----> Keyword used to declare an event.

EventHandler ----> Delegate; used when we got no information about the event. 

string name ="";

public string Name
            {
                get
                {
                    return name;
                }

                set
                {
                    name = value;
 
We want to raise that event whenever the property value (name) is change.

                    OnPropertyChange(this, new EventArgs());
                }
            }
 
onPropertyChange(this, new EventArgs()); ----> Run event once property's value is changed.

this ----> In the current context, the this keyword is used to reference the Person class object.

new EventArgs() ----> the EventArgs() class provides a value to use for events that do not contains event information.

}

3. In program class > Main event, type:

Person objP = new Person();

objP.OnPropertyChanged += objP_OnPropertyChange;
 
+= objP_OnPropertyChange ----> Add method named objP_OnPropertyChange to the event.

Quick tip ----> To automatically create the objP_OnPropertyChange method, after the += press: tab twice.

objP.Name = "Tony Stark";

4. Outside of the Main event, type:

static void objP_OnPropertyChange(object sender, EventArgs e)
{

 
object sender ----> Object from which the event came from (in this case , the event is raised on the change "name" property object from the Person class)

EventArgs e ----> Information about the event arguments

    Console.WriteLine("Sometimes you gotta run before you can walk.");
    Console.ReadLine();
}

Result: Sometimes you gotta run before you can walk.
 

C. Namespaces


namespaces allow us to have a set of class with the same name, separate from each other. In other words, namespaces prevents conflicts cause by having classes with the same name.

1. Create a new console application.

2. In Program.cs, outside the namespace ProgramName {...} , type:

namespace TeamA
{

    class Test
    {
        public static void Go()
        {

        }
    }
}

namespace TeamB
{

    class Test
    {
        public static void Go()
        {

        }
    }
}


3. In the Main method, type:

TeamA.Test.Go();
 
TeamA.Test.Go(); ----> Accessing the test class method from the namespace Team A

Quick tip: At the top with the other using statements, type:

using TeamA 

Now you can simply access your the "Test" class method by typing:

Test.Go(); 

You might have been using namespaces unconsciously; for example when you type: Console.WriteLine("..."); You have the using System keyword in your program. ​Indeed the Console class is present in the System namespace.
 

D. Inheritance


Why use inheritance you ask?

Lets say, you created a class with some properties and some methods. Now you want your other classes to have these methods and properties in them automatically. Well - you don't need to be a beautiful monkey to do that. Inheritance is here to help.

1. Create a new console application.

2. In program.cs, outside the Main method, type:

class Person
{

    public string Name;
   
    public void myMethod()
    {
        Console.WriteLine(Name);
        Console.ReadLine();
    }
}


class Employee : Person
{

    public string department;
}

 
class Employee : Person ----> Inheritance; a class cannot inherite from more than 1 class

Employee : Person ----> Class Employee is inheriting from class person.

Quick tip: Here the person class is the super class(base class) from which the Class Employee, the derived is inheriting.

3. In the Main method, type:

Employee objEmp = new Employee();
objEmp.Name = "Tom";

 
objEmp.Name = "Tom"; ----> Notice that the Class Employee, now contains the variables,methods and properties of class Person.

objEmp.department = "Software Engineering"; 
 
objEmp.department = "Software Engineering"; ----> While inheriting from class Person, the class Employee does not loss any of its own variables,methods and properties​.

objEmp.myMethod();
 

E. Protected Access Modifiers


1. Create a new console application.

2. In the Program.cs,outside of the Program class, type:

    class Person
    {
        protected string Name;
    }

3. In the Main event, type:

Program objP = new Program();
objP.Name = "Jake Roper";

         
objP.Name = "Jake Roper"; ----> Logical error "ApplicatioName.Person.Name is inaccessible due to its protection level".

Variables and properties with the Protected access modifier can only be accessed in the class where they have been defined (Person class). Unless they are inherited by other classes! 

4. To fix that logical error; Make the class Program inherite from the class Person.

class Program : Person

Challenge: Your mission should you choose to accept it, is to apply the following access modifiers. Feel free to report back your results in the comment section.
 
Modifier Class Subclass
Public
No modifier
Private
 
Hints:

1. A subclass is a derived class; for example we used the Program class as a Subclass in your previous exercise.

2. By default the private access modifier is selected when no access modifier is specified.
 

F. Reflection Basics


Do not panic, for the sake of this Outrageous C# tutorial, advance Reflection coding will be covered in the Ultimate C# tutorial.

Use of Reflection

Reflection is generally used by UI designers. In Microsoft Visual Studio when you drag and drop a button on a Windows Form or an ASP.NET application, the properties window uses reflection to show all the properties of that button such as its BackColor and BackgroundImage properties as shown in the screenshot below:



1. Create a new Console Application name MyReflection

2. In the myReflection namespace but outside of the Program class, type:

public class Employee
{

     public int ID { get; set; }
     public string FullName { get; set; }
}

3. Add the following using statement at the top among other using statements, in the program.cs file:

Using System.Reflection;

4. In the main method, type:

Type myType = Type.GetType("MyReflection.Employee");
 
Type myType = Type.GetType("MyReflection.Employee"); ----> Get information about the Employee class properties and store it in the myType variable

Type ----> Class 

.GetType ----> the method requires the Namespace.ClassName as a parameter to return information about the class's properties.

PropertyInfo[] myProperties = myType.GetProperties();
 
PropertyInfo[] ----> Store the Employee class's properties in an array of PropertyInfo data type.

myType.GetProperties(); ----> the GetProperties method is used to retrive the properties of the Employee class.

foreach (PropertyInfo item in myProperties)
{

      Console.WriteLine(item.PropertyType + " " + item.Name);
}


Console.ReadLine();

5. Run the application.

Results:

System.Int32 ID
System.String FullName
 

G. Abstract 


The keyword Abstract is derived from the English word abstraction which means removal.

Abstract classes

1. Create a new console application.

2. In the program.cs > program class, create an abstract class by typing:

Quick tips:
 
  • Abstract members like properties and methods cannot be private.
 
  • A class containing one or many Abstract members needs to be defined as an Abstract Class.

abstract class myClass
{
     public static string MyName { get; set; }

     public static void Hello()
     {
            Console.WriteLine("Hello World");
            Console.ReadLine();
     }
}


3. In the Main event, type:

myClass A = new myClass();
myClass.Hello();


4. Execute the application

Result: 

Kindly note that Abstract classes cannot be instantiated. Good thing that we used static properties and methods, just the following code from your program and your good to go:

myClass A = new myClass();

Nevertheless Abstract classes can be inherited by derived classes but we would get into that in the Ultimate C# tutorial for the sake of simplicity.
 

H. Threading


Thread = Light Process

To view the processes currently running on your Microsoft Windows operating system:

1. Right click on the task bar 

2. Click Start Task Manager.

To apply the concept of threading in your application:

1. Create a new Console Application.

2. Add the following using statement:

Using System.Threading

3. In program.cs, type:

static void WriteX()
{
     for (int i = 0; i < 2000; i++) Console.Write(" X");
}


4. In the Main Event, type:

Thread t = new Thread(WriteX);  
 
Thread t ----> Declare a new thread

new Thread(WriteX); ----> Initialize the thread with the WriteX method 
           
t.Start();
 
t.Start(); ---->Execute the WriteX() method           
          

DO SOMETHING WITHOUT WAITING for the WriteX method to finish running FROM THE Thread t.


for (int i = 0; i < 2000; i++) Console.Write(" O");

Console.ReadLine();



Result: 
 

I. Next Step


Feel free to apply all the concepts introduced to you in this tutorial using Microsoft Visual Studio Ultimate or Express.