Functions in C#

In C#, if you need to perform a specific task repeatedly in your code, then instead of writing same code for it it again and again, you can simply create a function that can perform the task. Then, whenever you want to do that specific task, you can simply call the function.

Every function in C# has two parts.

    1. Function Definition which includes code to be executed
    2. Function call

Function Definition

A function is first need to be defined before it can be called. Have a look at the following example to see how function can be defined and called.

using System;

namespace CSharpTutorials {
    class Tutorial {
            static void Main(string[] args)  {
				int result = performAddition(5, 10);
				Console.WriteLine("The result of addition is: " + result);
				Console.ReadKey();
            }
            public static int performAddition(int a, int b)   {
                return a + b;
            }
    }
}

Download the code

In the above code, a function named performAddition has been defined. A function definition consists of following parts.

Access modifier

This defines the level at which a function can be accessed by the other function and classes. The peformAddition function has a public access modifier.

The return type

This is the value that a function returns. It can be void as well which means nothing will be returned. The function defined in above code returns integer type value.

Function name

After the return type, comes the function name which can be anything and should follow identifier naming conventions.

Function Parameters

The last part of function definition is the function parameters. Function parameters are passed via arguments in the function call. They are basically used to pass some values to the function on which function can take action. In the performAddition function, integer ‘a’ and ‘b’ have been passed as parameter to the function.

Function call

You have to call function at the location in your code where you want to execute the functionality performed by the function.

A function is called by calling its name and by passing the required arguments to the function parameters if any. In above example, the performAddition function has been called inside the main function. Since the performAddition method takes two integer values, 5 and 10 has been passed to in the parenthesis that follow function name.

This function performs the addition of two integers and returns the value which has been printed using Console.WriteLine function on the console screen.

Arrays in C#

You can use variables to store small number of values. But if you have large data, it is not convenient use simple variables. Imagine you have to store names of all the students in a school and they are hundreds in numbers; it would not be wise to create hundreds of variables. In such cases, a collection of variables that can be declared at once will be handy. Array is basically such a collection. It can store data of similar types in the form of  a collection. Let us see how arrays are created, how data assigned to arrays and how items can be accessed within the array.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {
            // creating an array
            int[] array = new int[5];

            // another way to create array
            int[] array2 = { 10, 25, 35, 45, 55 };

            //accessing array elements
            Console.WriteLine(array2[3]);

            //assigning values to array index
            array2[3] = 100;
            Console.WriteLine(array2[3]);
            Console.ReadKey();
        }
    }
}

Download the code

Declaring an array is simple. You first specify the type of array, followed by opening and closing bracket and then the name of the array. In above example, an array of type integer and  named “array” has been declared.

Declaring an array is one thing but creating space for the array in the memory is another. This is done via new keyword followed by opening and closing bracket and the type of the array.

Once an array is created the next step is to assign elements to an array. It is imperative to mention here that an array has a zero based index which means that the first element of array is stored at the 0th index while the last element is stored and k-1st index where ‘k’ is the size of the array.

To assign value to an array, write the name of the array followed by the opening and closing brackets. Inside the brackets specify the index at which you want to store the element and simply assign it some value using equals operator. To access elements within the array, you only have to write the name of the array, followed by the index at which element is located.

Accessing array elements using for each loop

Here is a cool trick, if you want to iterate all the elements within an array, you can use foreach loop in the following way.

using System;
namespace CSharpTutorials {

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

            int[] numarray = { 10, 25, 35, 45, 55, 60, 33, 57 };
            foreach (int num in numarray) {
                Console.WriteLine(num);
            }
            Console.ReadKey();
        }
    }
}

Download the code

Nullable Types in C#

nullable data types in C# are similar to the other data types except they can store null values apart from the predefined data type. For instance if you create a nullable integer variable, you can store an integer as well as a null value in that variable. Normal variables can be specified as nullable by simply appending a question after the type specification. Consider following example to understand the concept.

using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {
            int? var1 = null;
            int? var2 = 10;
            int? var3 = null;
            bool? on = null;

            Console.WriteLine("The int variable var1, var2 and var 3 contains {0}, {1} and {2}", var1, var2, var3 );
            Console.WriteLine("The bool variable on contains " + on);
            Console.ReadKey();
        }
    }
}

Download the code
In the above code, three nullable integer type variables have been declared i.e. var1, var2 and var3. The first and third variable stores null while the second one stores 10. Now, if these variables are printed on screen, you will see that nothing will be printed in their place. Similarly, boolean variable ‘on’ has also been assigned a null value which when printed on console will not be displayed.

Null Coalescing Operator

In addition to nullable types, C# contains Null coalescing operator which is used to store some other value in the operand if the first value null. Coalescing operator is denoted by double question marks. Have a look at the following example.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {
            int? var1 = null;
            int? var2 = 10;
            int? var3 = null;

            var3 = var1 ?? 15;
            Console.WriteLine("The variable var3: "+var3);

            var3 = var2 ?? 20;
            Console.WriteLine("The variable var3: " + var3);

            Console.ReadKey();
        }
    }
}

Download the code
In above example again var1 and var3 contains null while var2 contains 10. The value of var1 is stored in var3 with the addition of coalescing operator which says that if var1 contains null, store value 15 in var3. Var3 is then displayed on console which shall display 15. Next, value of var2 is stored in var3 and this time coalescing operator stores 10 in var2 if var2 contains null. But since var2 contains 10, therefore 10 will be stored in var3 and will be consequently displayed on console.

Structures in C#

Often times you need to store different types of data which is related to each other. For instance you may need to store name, age, salary and department of an Employee. You will require four variables to do this. These four variables tell you information about one employee. For 2 Employees, you will require 8 variables. This is extremely cumbersome. Such cases are handled using structures.

A structure in C# is a data type which can contain multiple variables of different data types. Let’s see how function can be used to store employee information.

using System;

namespace CSharpTutorials {

    struct Employee  {
        public string emp_name;
        public int emp_age;
        public int emp_salary;
        public string emp_department;
    }

    class Tutorial {
        static void Main(string[] args) {
            Employee employee1;
            Employee employee2;

            employee1.emp_name = "Mike";
            employee1.emp_age = 30;
            employee1.emp_salary = 100000;
            employee1.emp_department = "sales";

            employee2.emp_name = "Jasmine";
            employee2.emp_age = 23;
            employee2.emp_salary = 200000;
            employee2.emp_department = "marketing";

            Console.WriteLine("Name of Employee1:" + employee1.emp_name);
            Console.WriteLine("Age of Employee1:" + employee1.emp_age);
            Console.WriteLine("Salary of Employee1:" + employee1.emp_salary);
            Console.WriteLine("Department Employee1:" + employee1.emp_department);

            
            Console.WriteLine("\n\nName of Employee2:" + employee2.emp_name);
            Console.WriteLine("Age of Employee2:" + employee2.emp_age);
            Console.WriteLine("Salary of Employee2:" + employee2.emp_salary);
            Console.WriteLine("Department Employee2:" + employee2.emp_department);

            Console.ReadKey();
        }
    }
}

Download the code
In the above code a structure named Employee has been defined. To define a structure, you have to use keyword struct. Structures are value types which mean that there is no need to use new keyword in order to create a structure if all the structure variables are assigned some value before structure is used. However, new> keyword is required if you want to use structure before assigning value to all of the members of the structure.

To access the variables withing the structure, write the name of the structure variable, followed by a dot and the name of the variable.

Apart from variables, a structure can also contain functions. This is explained in the following example.


Download the code

In the above example, two functions have been added to the Employee structure. The storevalues method stores value in the member variables of the structure, while the displayinfo method displays values of all the member variables on the console screen.

Strings in C#

Simply put, string in C# is nothing but a sequence of characters. Strings are extremely useful. They can be used to store name of persons, place or any other string type value. There are multiple ways for creating string in C#, they have been explained in the following example.

using System;
namespace CSharpTutorials {

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

            // string using string literals
            string first_name = "john";
            string last_name = "arryn";

            //string creation using concatenation
            string fullname = first_name + " " + last_name;
            Console.WriteLine(fullname);

            //string creation via character array
            char [] chararray = { 'a', 'b', 'c', 'd', 'e' };
            string str = new string(chararray);
            Console.WriteLine(str);

            // String creation by joining string arrays
            string[] strarray = { "this", "is", "string", "array" };
            string joinedarray = string.Join(",", strarray);
            Console.WriteLine(joinedarray);
            Console.ReadKey();
        }
    }
}

Download the code

The most simplest method of creating a string is by storing a string literal in it. In the above code the string variable first_name contains a string literal “john”. A string can also be created by concatenating two strings via “+” operator.

Strings can also be created by passing character type array to the constructor of the string class. In the above example, character type array named “chararray” is used to create string array “str”. Finally, strings can also be created by using “join” extension method of string class. This method takes two parameters. The first one is the string that you want to append after each string item in the array and the second parameter is the string to join.

String Functions

There is a huge number of functions that can be used to manipulate strings. Some of these functions have been explained in the following example.

using System;
namespace CSharpTutorials {

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

            string car = "FoRd";

            // convert all  to upper case
            car = car.ToUpper();
            Console.WriteLine(car);

            //convert all to lower case
            car = car.ToLower();
            Console.WriteLine(car);

            //finding length of the string
            int len = car.Length;
            Console.WriteLine(len);

            // Inserting string within a string.
            car = car.Insert(1, "abcd");
            Console.WriteLine(car);

            Console.ReadKey();
        }
    }
}

Download the code

Enumerations in C#

Enumerations in C# are used to hold collection of values where each value corresponds to an integer.

MSDN defines enum as: An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

This might seem complex at the beginning but the concept is quite simple. Consider a scenario where you want to store months in a year and you want to make sure that when you write January, you get integer 1; similarly for February you get 2. In such cases, enumerations can be very handy. Have a look at the following example.

using System;

namespace CSharpTutorials {
    enum months { Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec };
    class Tutorial {
		static void Main(string[] args) {
			months monthofyear;
			monthofyear = months.Apr;

			int firstmonth = (int)months.Jan;
			int lastmonth = (int)months.Dec;

			Console.WriteLine("January is the: {0} month.", firstmonth+1);
			Console.WriteLine("December is the: {0} month.", lastmonth+1);
			Console.ReadKey();
		}
	}    
}

Download the code
Enumerations are created using the keyword enum followed by the name of the enumeration and curly brackets, respectively. Inside the curly brackets, the items of the enumeration are listed in the form of string literal. Each item is separated by a comma. In the above code, an enumeration named months has been defined which contains months within a year.

Enumeration variable can only contain one of the values of the enumeration. In the above code monthofyear variable of enumeration of type months have been defined and the month of Apr has been assigned to it.

Like arrays, enumerations follow zero based index which means that the integer value for first item is zero and for last item is k-1 where k is the size of the enumeration. Therefore, you need to add one to the integer value of enumeration item, in order to get actual associated integer value of the enumeration.

Few other facts about C# enums:

  • Enums can’t inherit from other enums. All enums are inherited from a built in System.Enum
  • To get the int value of an enum, simply cast in to int using (int) prefix. Here is an example.
  • You can use: Enum.GetNames (typeof (MyEnum)) to get an array of all possible names inside the enum. Then you can use .Length property of the resulting array to get the size of the enum.
  • You can use: Enum.GetValues (typeof (MyEnum)) to get an array of all possible values inside the enum.
  • Enum declaration can optionally be decorated with [Flags]. This will enable the enum to represent a collection of flags as opposed to a single value. These collections then can be manipulated using bitwise operators. Also once you decorate the definition of an enum using [Flags], you can use ToString() function to extract the name of the enum in string format. This is very handy in situations where string representation of the enum and manipulation is needed. Here is some nice discussion about [Flags] on stack overflow.

Access Modifiers in C#

Access modifiers are used to specify the level at which each variable, function or object can be accessed within the application. In C#, there are five types of access modifiers which are as follows:

  • public
  • private
  • protected
  • internal
  • protected internal

Public Private

Class or members specified as public can be accessed by other functions and objects anywhere within the application. On the other hand, members defined private can only be accessed within the class in which they are defined. Have a look at this example to understand this concept.

using System;
namespace CSharpTutorials {
    public class Person {
        public int age;
        public string name;
        private int salary;

        public Person(int age, string name, int salary) {
            this.age = age;
            this.name = name;
            this.salary = salary;
        }
    }

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

            Person p = new Person(20, "John", 100000);

            Console.WriteLine("The age of person is " + p.age);
            Console.WriteLine("The name of person is " + p.name);

            /* The following code will not executed 
             * because salary is private member of person class
             * 
             * Console.WriteLine("The salary of person is " + p.salary);
             */
            Console.ReadKey();
        }
    }
}

Download the above code

In the above code a class named Person has been created. This class has three member variables: age, name and salary. First two variables age, and name are public while salary is private.

Inside the Tutorial class, Person object ‘p’ has been created. Since age and name are public member variables of Person class they can be accessed inside Tutorial class and can be printed on the console. However, salary is a private variable, therefore it cannot be accessed inside the Tutorial class via dot operator.

Protected

protected member variables and classes can only be accessed within the classes in which they are defined and inside the child classes. This concept will be explained with the help of inheritance in upcoming chapters.

Internal

internal access modifier is used to make variables and functions accessible within the assembly of the class in which they are defined. Have a look at the following example:

using System;
namespace CSharpTutorials {
    public class Person {
        internal int age;
        internal string name;
        internal int salary;

        public Person(int age, string name, int salary) {
            this.age = age;
            this.name = name;
            this.salary = salary;
        }
    }

    class Tutorial {
        static void Main(string[] args) {
            Person p = new Person(20, "John", 100000);

            Console.WriteLine("The age of person is " + p.age);
            Console.WriteLine("The name of person is " + p.name);

            Console.WriteLine("The salary of person is " + p.salary);
            Console.ReadKey();
        }
    }
}

Download the above code

In the above code Person class has three member variables age, name and salary. All of these three variables are accessible within the Tutorial class because both Person and Tutorial classes are within the same assembly.

Protected Internal

protected internal access modifier is a combination of protected and internal modifier. It makes a variable accessible to the child classes that are inside the same assembly of the class in which they were actually defined.

Loops in C#

If you want to execute your code repeatedly certain number of times or until a certain condition is met, you can use C# iterative statements which are also known as loops.

There are three types of loops in C#.

  • For loop
  • While loop
  • Do-While loop

For Loop

For loop is usually used when you already know the number of times you want to repeat the execution of your code. For instance if you want to print the table of 7, you know that you will have to repeat your multiplication logic 10 times. Consider following example:

using System;

namespace CSharpTutorials {
    class ForLoop {
        static void Main(string[] args) {
            for (int i = 1; i < 11; i++)  {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
            }
            Console.ReadKey();
        }
    }
}

Download the above code

For loop starts with the keyword “for”. It has three parts: Initiation statement, test condition, and increment statement which are separated by a semicolon. Here i=1 is initiation statement, i<11 is test condition and i++ is increment statement. For loop keeps on executing until the test condition returns false.

While loop

While loop keeps on executing until a certain condition is met. In the next example the table of 7 is printed using while loop.

using System;

namespace CSharpTutorials {
    class WhileLoop {
        static void Main(string[] args) {
            int i = 1;

            while ( i < 11) {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
                i++;
            }
            Console.ReadKey();
        }
    }
}

Download the above code

In while loop the initiating statement is written before the while loop and the increment condition is written inside the loop. During each execution the test condition is checked and if it returns true, the code inside the loop is executed.

Do-While loop

Do-While loop is similar to while loop but in Do-While loop the test condition is evaluated at the end of the loop which means that the code inside the loop is executed at least once. Let us see how the table of 7 can be printed on console screen via do-while loop.

using System;

namespace CSharpTutorials {
    class DoWhileLoop {
        static void Main(string[] args) {
            int i = 1;
			do {
                Console.WriteLine("7 x " + i + " = " + 7 * i);
                i++;
            }
            while (i < 11) ;

            Console.ReadKey();
        }
    }
}

Download the above code

It can be seen in the above code that the while statement has been appended at the end of the loop and test condition is being executed there. At the start of the loop, the keyword “do” specifies that it is a do-while loop.

C# Decision statements

Decision statements are used to control the flow of execution of the code. These statements are used to execute particular piece of code if or if not a certain condition is met. There are four major types of decision statements in C#.

  • If statement
  • If/else statement
  • Else if statements
  • Switch statement

If statement

If statements are used when you want to execute or exclude piece of code if a certain condition is met or not. Have a look at this example.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            string sky = "blue";
            if (sky == "blue") {
                Console.WriteLine("It is day time.");
            }
            Console.ReadKey();
        }
    }
}

In the above code, a string variable named sky has been initialized to value of “blue”. It is then checked that if the sky variable contains “blue” the console screen shall print “It is day time.” If sky variable contains something else, nothing will be printed.

Download the above code

IF/Else Statement

In the last example, what if we want something else be printed if sky variable contains value other than “blue”? In such cases if/else statements are used. Have a look at this example.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            string sky = "grey";

            if (sky == "blue") {
                Console.WriteLine("It is day time.");
            }
            else {
                Console.WriteLine("The sky is not clear.");
            }
            Console.ReadKey();
        }
    }
}

Download the above code

In the above code if “sky” variable contains value other than “blue”, the console screen shall print that “The sky is not clear.”

Else If

A sky can have multiple colors, what if we want to print different statement depending upon the color of the sky? Such a scenario can be handled by using else if statements. Consider the next example.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            string sky = "grey";

            if (sky == "blue") {
                Console.WriteLine("Weather is clear");
            }
            else if (sky == "grey") {
                Console.WriteLine("Weather is cloudy");
            }
            else if (sky == "black") {
                Console.WriteLine("It is night");
            }
            else {
                Console.WriteLine("No information about weather.");
            }
            Console.ReadKey();
        }
    }
}

Download the above code

In the above code, the sky variable is initialized to “grey”. If and else if statements are being used in conjunction in order to handle blue, grey, black and other values of the sky.

Switch Statements

If large number of  “if” and else if statements are required to implement a logic, it is more convenient to use switch statements. In switch statement the value to be compared is passed as a parameter to switch statement. This value is then compared with each case statement and the case statement whose value matches with this passed value, is executed. Let us see how the sky color example can be implemented via switch statement.

using System;
namespace CSharpTutorials {
    class Tutorial {
        static void Main(string[] args) {

            string sky = "grey";
            switch (sky) {

                case "blue": {
                        Console.WriteLine("Weather is clear");
                        break;
                    }
                case "grey": {
                        Console.WriteLine("Weather is cloudy");
                        break;
                    }
                case "black": {
                        Console.WriteLine("It is night");
                        break;
                    }
                default: {
                        Console.WriteLine("No information about weather.");
                        break;
                    }
            }
            Console.ReadKey();
        }
    }
}

Download the above code

C# Tutorial

What is C#

C# or CSharp is an object oriented programming language from Microsoft. C# is greatly inspired by C and C++ in terms of functionality and syntax. If you have programmed in any of the aforementioned languages, you will easily find your feet in C#. This C# tutorial is for beginners as well as advanced programmers, who want to learn C#.

Consider this basic C# program to understand the language syntax.


Download the above code

A typical C# program consists of the following parts.

Identifiers

In the above code, System, CSharpTutorials, BasicSyntax, Main, WriteLine and ReadKey all are identifiers. These are the names by which programmers declare their namespaces, functions, classes, member variables and so on.

Keywords

In C#, Identifiers start with an alphabet or underscore. C# is a case sensitive language therefore MyVariable and myvariable are not equal. By convention, function parameters, local variables and all the private fields should be declared in camelcase while the rest of the identifiers should be declared in Pascal case.

Keywords are reserved words in C# language. We use them for specific purposes by default. We should not use these words as  identifiers. We use the using keyword to add namespace in C# program. Here “using”, “class”, “void” and “static” are keywords.

Punctuators

We use punctuators to structurally demarcate your code. There are two punctuators in the aforementioned example which are  “{ }” and “;”. Use braces for creating a statement block by grouping multiple lines of codes while semicolon is used to terminate line of code.

Literals

Literals are lexically embedded into C# code. Literals consist of primitive data. In The sample code, the statement “Welcome to C#” is a literal string. It can be anything and do not have any logical impact on the code. Integers can also be used as literal. For instance you can write statements like “2+2” in your code. Here 2 is a literal value.

Operators

Operators are functions that act upon literals or variables and return the result of the operation they perform. We denote operators with symbols. For example we denote an addition operator by a “+”.

Comments

In C#, we use comments to explain what is happening in the code. C# never executes commented code. There are two types of comments in C#:

  • Single line comments: Entire line after //
  • Double line comments which start with /* and end with */.
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .