Web Design that taps into the haromny and vision of your dreams.

C# Programming Fundamentals

By on in Coding

2,449 words, estimated reading time 12 minutes.

Introduction to Programming with C# Series
  1. Introduction to Programming with C# 7
  2. C# Programming Fundamentals
  3. Introduction to Object-Oriented Programming
  4. C# Object-Oriented Programming Part 2
  5. Flow Control and Control Structures in C#
  6. C# Data Types, Variables and Casting
  7. C# Collection Types (Array, List, Dictionary, Hash Table)
  8. C# Operators
  9. Using Data in C# 7 with ADO.Net & Entity Framework
  10. LINQ: .NET Language Integrated Query
  11. Error and Exception Handling in C#
  12. Advanced C# Programming Topics
  13. Reflection in C#
  14. What Are ASP.Net Webforms
  15. Introduction to ASP.Net MVC
  16. Windows Application Development
  17. Assemblies in C#
  18. Working with Resources Files, Culture & Regions
  19. Regular Expressions in C#
  20. Introduction to XML with C#
  21. Complete Guide to File Handling in C#

In this tutorial, we will have a look at the various data types you can use within C#, how to declare variables and how to convert certain types to other types. We will also look at functions and a few keywords.

Variables

C# is a type-safe programming language which means that each variable must be declared, and once declared a variable of a given data type cannot be changed to another type. This allows the compiler to check your code, before it is compiled, for some errors that will result in a program crash.

It is good programming practice to use a variable for one given "task" and to create a new variable for a different task. It also enforces code maintainability by guaranteeing that a variable's data type is constant.

Variables are declared by first specifying the type, then the name by which it will be accessed. You can optionally include an access modifier which limits the scope of the variable. Two of the most common are public and private. As the name may suggest, public variables can be accessed by anyone, whilst private can only be accessed within the current scope (the function or class it is declared in.)

int myNumber;
string myString;
decimal accountBalance;

When declaring variables like this they will be given the default value based on their type. Typically this 0 for numbers or empty strings. We'll have a look at the various basic types and their default values later on. You can give a variable an initial value by adding an assignment to the declaration as shown in the example below.

int myNumber = 1;
string myString = "Some test string";
decimal accountBalance = 1.0M;

Because C# is a type-safe language, you will not be able to assign a string to a variable.

int myNumber = "Hello World"; //This will not compile

You can also assign a variable the value of another variable of the same type.

int x = 5;
int y;
y = x;

Variable assignment assigns the values of x to y. X will still retain its original value; Y is just given the value of X.

Data Types

In the .Net framework, there are many different types you can use to hold data, from numbers, strings, dates and much more. We will cover the data types in more detail in a later tutorial, for now we'll just look at a few basic types.

There are two broad categories that a data types can be: value types and reference types.

A value type directly contains its data. A variable of type int contains a value (e.g. 12345) and only a value. Each variable of a value type has its own copy of the data. An operation on one variable does not affect another. Value types are stored in a memory location known as the stack.

Examples of Value types are int, float, struct, and enum.

Reference types contain a reference, or memory location, of their data. The data is stored as an object on the heap. Unlike value types, two or more reference types can point to the same memory location, thus an operation on one variable can affect another. Reference types are instantiated with the new keyword.

Examples of Reference types are string, arrays, classes and delegates.

It is important to know the difference because it affects how you can manipulate the data each type holds.

If x is a variable and its type is a value type, then changing the value of x directly changes the data it contains.

If x is a variable and its type is a reference type, then changing the value of x is not the same as changing the data in the object which the value of x refers to.

I know that may be a bit heavy to some, but it's an important concept to understand.

Functions

In the previous tutorial, we wrote a simple hello world program in which we saw the Main method. We didn't explain anything about what the Main method is or what it does.

The "Main" is a method that must exist in every program, as the compiler uses this to decide what to do when the program runs. This is called the entry point for the program.

Let's have a reminder and have a look at our Hello World again.

using System;
 
class HelloWorld
{
  static void Main()
  {
    Console.WriteLine("Hello World!");
  }
}

The M is capital and is case sensitive. The Main method must always be marked as static otherwise it cannot be run. Static means the method can be called without an instance of the class.

The next word, Void, is the data type that the method returns, and in this case, void means nothing is returned). If the method was to return a number then you would replace void with int.

All Methods are blocks of code, and a block of code is always encased within curly brackets (braces).

Methods are always executed from the top brace down to the bottom brace, in sequential order. When the compiler reaches the end of the Main method, the program exits.

We can add another method to our project in much the same way as the Main method. After the closing brace of the Main method, we will add in another method called "myMethod". Within this method, we will write a line to the console stating that myMethod has been called. We will then call myMethod from the Main method.

The code should look like this when you add our new method.

using System;
 
class HelloWorld
{
  static void Main()
  {
    Console.WriteLine("Hello World!");
    myMethod();
  }
 
  static void myMethod()
  {
    Console.WriteLine("myMethod Called");
  }
}

When running the program you should see something similar to this.

Hello World Output
Hello World Output

Passing Parameters to Methods

What do we do if you want to pass some data to your new method and have it return a value back? How do you capture the result? And how do you pass a parameter? Let's have a look using a simple program to add numbers.

Starting off with a new console project, we are going to create a method called addNumbers which will take two integers as parameters. This is done by defining a variable within the brackets of the method. Parameters are separated by a comma.

static void addNumbers(int x, int y)

This will tell the compiler that the addNumbers method will need to have two integers, x and y. This method can only be called with the correct number of parameters, and they must be of the right type.

addNumbers(); // Will not work as there are no parameters
addNumbers(5); // Will not work as the method requires two parameters
addNumbers("1", "2"); // Will not work as these are strings
addNumbers(5, 5); // Will work 
 

You can copy this code over the top of the Hello World program if you like, or you can create a new project.

using System;
 
class AddNumbersProgram
{
    static void Main()
    {
        addNumbers(5, 5);
    }
 
    static void addNumbers(int x, int y)
    {
        int z = x + y;
        Console.WriteLine($"Result of {x} + {y} = {z}");
        Console.ReadKey();
    }
}

When run this program should show:

Result of 5 + 5 = 10

We have used $ to indicate a string interpolation here. This is a shorthand notation for treating a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions or variables. When an interpolated string is resolved as a result string, items with interpolated expressions are replaced by the string representations of the expression results.

You can also use the string.Format function to achieve the same result.

string.Format("Result of {0} + {1} = {2}", x, y, z);

You should avoid string concatenation, that is appending one string to another, as it can be very costly to compute and will result in poor application performance. If you need to build strings, use string.Format or interpolated strings.

Returning a Value

Instead of outputting the calculation to the screen, you may wish to return it back to the calling method (the method where the addNumbers method was called from. In this case Main).

We need to make a few changes to the method. We need to change the word void (which means the method does not return a value) into int (which means the method returns an integer number). The method declaration now becomes:

static int addNumbers(int x, int y)

Now we need to remove the Console.WriteLine line and replace it with:

return z;

Finally, we need to capture the return result within Main.

int result = addNumbers(5, 5);

And that's all we need to do to make our method return a value. We just need to change our calling function to pick up the result.

using System;
 
class AddNumbersProgram
{
    static void Main()
    {
        int result = addNumbers(5, 5);
        Console.WriteLine("Result of addNumbers = {0}", result);
    }
 
    static int addNumbers(int x, int y)
    {
        int z = x + y;
        return z;
    } 
}

If a method is to perform a calculation, it is far better to have it return the result on its own, rather than including formatting and other information, as the result on its own can be used from any other methods that may need to use the same calculation. By returning the formatted string, you are limiting that method to that particular task.

Variable and Object Naming Guidelines

Variable, method and class names have rules that govern how they should be named.

They must:

  • Be Unique
  • Start with a letter or underscore, they must not start with a number
  • Contain only letters, numbers and the underscore character
  • Not be reserved words or keywords

As well as those rules, there are some recommendations as well, for good practice and readability. Some of these are listed below:

  • Names should always be meaningful, but not too verbose.
  • You should not use single letter identifiers except for loop control (where you should use i,j and k) or for mathematical equations (e.g. x = x * y^2).
  • You should always use the data type most appropriate for its use. For example, a variable to hold the day of the month would never rise above 31, so a byte would be a better data type over an int or decimal.

Using Namespaces in C#

The entire .Net framework is built using namespaces, the most important of which is System. A Namespace is a construct that can be used to organise sections of code, be it classes, structs, other namespaces or even entire solutions. Namespaces are used to avoid code conflicts and to group together classes of similar functionality. It is good practice to implement namespaces in your projects, as it will aid code reuse in later projects.

Standard Namespaces

Let's have a play with our Hello World application in Visual Studio.

Remove the line using System; and hit Ctrl+Shift+B again to build the project. You'll notice that the compiler now flags up an error.

The name 'Console' does not exist in the current context

This is because the Console object exists within the System namespace. Since we have not told the compiler where to find the Console it raises an error.

There are two methods to fix this problem. We can either add System before the Console object:

System.Console.WriteLine("Hello World!");

Or a better method would be to use the "using" directive. This is because a namespace can contain another namespace, which can contain another namespace. This will lead to a large amount of unnecessary code typed in.

The first method of calling System.Console.WriteLine uses the fully qualified name, which is very similar to a telephone number consisting of country code plus area code. The compiler knows exactly where to find the Console. The second method, using System, tells the compiler to look in a namespace for the object.

You may have also noticed that Visual Studio Editor has put a wavy line under the word Console. This is its way of telling you where the problem lies. It is a very similar wavy line to the spell checker in Word. If you click on Console when it is underlined, you should see a yellow line appear under the last letter. If you now place your mouse over this yellow box an icon will appear with a drop-down arrow next to it. Click on the arrow and Visual Studio will prompt you for different ways of fixing the problem.

IntelliSense
IntelliSense

In this example, it is asking us to select "using System" or "System.Console". If you select one of these actions, the editor will change the code accordingly. Hit Ctrl+Shift+B again and see how it now successfully compiles.

In later tutorials we will use other namespaces; a few are listed below as an example.


System.Data.SqlClient - Database Connection Objects
System.IO - Input / Output Objects
System.Xml.Schema - XML Reader and Writer Objects

Implementing a Namespace

As I said previously, it is good practice to implement namespaces in your projects, so let's have a look at how to implement a namespace in our hello world application.

using System;
 
namespace MyHelloWorld
{
  class HelloWorld  
  {
    static void Main()
    {
      Console.WriteLine("Hello World!");
    }
  }
}

It's that easy! Just surround your classes with a namespace block and you're done.

In fact, it can be even easier with a nice feature of the IDE. Simply select the classes you wish to include in the namespace to right-click the code with the mouse and select "Surround With..." and type namespace. The IDE will automatically add in the namespace construct, braces and indent the code for you!

Avoid Conflicts

Namespaces are primarily used for avoiding code conflicts. You could have two developers working on different parts of the same project. They could potentially use the same class name for something inadvertently, and namespaces would be able to resolve the correct class.

Alternatively, you could be using third party software from two companies, and they could use the same class names. Each different class with the same name would perform a slightly different function.

Example

This very simple example illustrates the use of two classes of the same name, which each have a function of the same name. By referencing the namespace you can access the other class's methods directly and unambiguously.

using System;
 
namespace myInhouseCode
{
    class myClass
    {
        static void Main()
        {
            Console.WriteLine("myInhouseCode Main");
            myMethod();
            myContractorsCode.myClass.myMethod();
            Console.ReadLine();
        }
 
        static void myMethod()
        {
            Console.WriteLine("myMethod Called From myInhouseCode");
        } 
    }
}
 
namespace myContractorsCode
{
    class myClass
    {
        public static void myMethod()
        {
            Console.WriteLine("myMethod Called from myContractors Code");
        }
    }
}

The output of this code is as follows:

Multiple Namespaces
Multiple Namespaces

In this example, we can see that although we have two classes of the same name, and two methods of the same name, by using namespaces we can avoid conflicts, as namespaces allow us to explicitly find the function we require.

Last updated on: Thursday 11th October 2018

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.