Posts in Category: c

c# – Methods, Classes, and Namespaces

When programming it is essential to organize and structure your code, otherwise it will become unwieldy to work with.

c# offer a number of ways to structure and and organize our code using:

  • methods
  • classes
  • namespaces

Methods are used for storing blocks of codes and each method is designed to perform a specific task (aka function).

Methods, in turn, are stored in “classes”. These classes class can store one or more methods.

Classes in turn are stored in “namespaces”. You can think of Namespaces as a bit like folders on a windows machine. That means that namespaces have tree structures where a namespace can house classes as well as other lower-level namespaces. As a result we have the following hierarchy:

namespaces => classes => methods

One of the key strength of c# is that it has


c# – Create a variable that can only hold a fixed set of values (aka an Enum Constant)

A enum constant is a special kind of variable that can only take a set number of values, e.g.:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class EnumConstantDemo
    {
        // notice that you have to place this outside the method, othewise the method
        // wont recognise this a enum constant (aka variable type)
        enum Colour
        {
            red,
            green,
           															

c# – Intro to Exceptions

Sometimes you might have a block of “dangerous code” in your program. These are code that could fail. When these blocks of “dangerous codes” fail, it will stop the program straight, and won’t attempt to carry on any further, and instead it will just output an error message.

However sometimes you might want your program to do some (or all) of the following when the “dangerous code” fails:

– continue with the rest of the program
– run a specific block of code when a failure occurs (aka error-handling)
– Customize the error message that get’s outputted.
– Create artificial error messages, that simulates a failure, when in fact, there is none. E.g. say you have a string variable called “FirstName”. A valid entry for this is “Mr”. However you want this


c# – Storing data inside objects (by using “fields”)

Whenever you create an object (aka an instance of a class), you often want to store data within that object. You can think of this info as the object’s metadata. For example, lets say want to have a class called “Employee”, and you want to use that class to create “employee” objects, and each employee-object needs to store the following info:

firstname
age
DateJoined
Salary

Note: the words “instance” and “object” are synonyms.

In order to make this possible, you first need to write your Employee class to accept this info. After that, you can call on the class to instantiate the object and pass the metadata into it.

There are a number of ways to write your

1st Approach: Store the data directly in an object, using “Fields”

In this approach we have declared inside


c# – Declare variables outside if-else statement scope

If you declare (and initialize) a variable within an if-else statement, then that variable’s value will only exist within that if-else statement. However if you want to initialize (i.e. assign a value to) the variable within the if-else statement, but want to make the variable accessible outside the if-else scope, then you need to first declare the variable, in the highest most scope where you want to make the variable accessible, and then initialize it within the scope, here’s an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
    {
        static void Main(string[] args)
        {

			string ContainsSeedsSentence;   // Have to declare this outside if-else statement.
   															

c# – The Interface

We previously came across the concept of inheritance, which is where a child class (implicitly) inherits the properties and methods from it’s parent class.

However what if you don’t want a class to inherit methods and properties, but we do want class to have certain members (properties and methods) with particular names. That’s where “interfaces” comes in.

If you want to create a collection of classes and you want them all to have methods of certain names (although the content of the methods can be completely different), then you use interfaces.

A common example of where interfaces comes in handy is when you create a class (e.g. called DBclass) that’s designed to interact with a db and perform crud operations. For this class you might have a method called “Read()” for retrieving data


c# – Storing data inside objects (by using “Properties”)

Previously we looked at how to store data in an object using fields. Fields are easy to use, but only if you set them to public. Having public fields is bad practice.

To overcome this we can set the fields to private and then write (public) methods within the class to access/modify the fields. This approach keeps the fields private, but unfortunately it is a much more messier solution….that requires writing a lot more code, and is more harder to follow.

That’s where “properties” comes in to save the day. Properties, gives you the best of both worlds, i.e.:

  • It keeps the object’s data private
  • It keeps the syntax simple and has minimal overhead in terms of number of lines.

Properties are type of class member that is specifically used for storing an object’s


c# – The “this” keyword

Earlier we cam across the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Employee
{
    public string Firstname { get; set; }
    //Note, the above line is the shorthand way of writing the following:
	//
	//   private string firstname;   // here we are defining a property called "firstname"
    //   public string Firstname
    //   {
    //        get{return firstname;}
    //        set{firstname = value;}
    //   }
	//
	// The same could be done for the following two lines

	public int Age { get; set; }
    public double															

c# – Abstract Classes

When you organise your code into parent and child classes (in order to fully utilize the concept of inheritance in order to cut down code duplication), you may end up with parent classes, that are just there for the purpose of holding base-class code. The class itself isn’t needed for instantiating objects.

These types of class (which you never instantiate objects from) are referred to as “abstract classes”. You never use an abstract class directly to initialize an object.

Here is an example of abstract classes in action:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractClass1
{

    // hwer
    public abstract class Employee
    {
        public string Name { get; set; }
  															

c# – Instantiate an object and set it’s Properties simultaneously (using the Initialization approach)

 

1st Approach: Using Initialization

Here we use properties (as demonstrated in the previous), but this time we set all the properties in one go, by writing them as part of the object’s actual declaration, using curly-bracket syntax:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Employee
{
	public string Firstname {get; set;}
	public int Age {get; set;}
	public double Salary {get; set;}
}

class Program
{
    static void Main()
    {
        Employee Dave = new Employee()
		{
			Firstname = "David",
			Age = 35,
			Salary = 35235.23
		};
		// Using the above syntax is called initialisation

        Console.WriteLine("{0} is {1} years old and earns  £{2} per year.", Dave.Firstname, Dave.Age.ToString(), Dave.Salary.ToString());
    }
}