Complete Beginners Guide to C#

  • Home
  • Complete Beginners Guide to C#
banner
banner
banner

Complete Beginner's Guide to C#

Introduction to C#

C# (pronounced C sharp) is one of the most widely used programming languages for .NET frameworks. It is a modern, object-oriented, multi-paradigm programming language developed by Microsoft in the year 2000. It is extensively used for building Windows applications, mobile applications, games, web services, enterprise software, etc. 

Why C#?

C# has several advantages for the programmers. These advantages mainly include saving your time, low learning curve, scalable language - easy to maintain, large community, object-oriented. One should opt for C# because it comes with plenty of career opportunities and even the future looks bright. This is a lovable language as programmers agree to the fact that committing to a job in programming with C# is a satisfying process. 

Applications of C# 

There are many applications of C#. these are -

  • Web Applications
  • Windows Client Applications
  • Windows and Web Services
  • Windows Store Apps
  • Mobile Apps
  • Enterprise Cross-Applications Development
  • Cloud and Azure

Any prerequisites?

There are no necessary prerequisites for learning C# other than knowing the OOPs concept. But, basic knowledge of C or C++ would be a plus point as it would make the path of learning a little bit easier. 

.NET Framework

.NET is a software framework, designed and developed by Microsoft, and in the year 2002, on February 13th, its first version was introduced - .NET Framework 1.0. It’s a virtual machine used for compiling and executing programs that are written in programming languages such as C#, VB.NET, etc. 

Visual Studio Installation Guide 

Step 1: Check for Visual Studio prerequisites

Step 2: Download Visual Studio by going to this link - https://visualstudio.microsoft.com/downloads/. Select either community edition (free) or professional edition (30 days free trial). I'm using Visual Studio 2022 for this articl.

Step 3: After the download is complete, open the .exe file. 

Step 4: By clicking on “Continue” on the next screen, start the installation. 

Step 5: After installation is complete, select the software version on the next screen. 

Step 6: Select desktop version in the next screen, click “.NET desktop development”, then install. 

Step 7: After all the files are finished downloading, click on the restart on the next screen and reboot your PC. 

Step 8: Once the reboot is complete, open visual studio, choose a theme and start the visual studio. Start developing by going to the File menu. 

First console Program in C# - hello world program

A console application can be executed in the Windows command prompt. For anyone new to .Net, building a console app is ideally the first step, to begin with. We will use Visual Studio to create a console project. Next, we will use the console app to display the message "Hello World". We will then learn how to build and run the console app. Let's follow these steps to put this example into place.

Step 1: Step one is to create a new project in Visual Studio. For this, once Visual Studio is launched, you should choose the “create a new project” option.

Step 2: The following step is to choose the project type as the “Console app”. You must include the name and location of your project. Click on the Next button, and select your Framework version. I have used .Net core Framework 3.1 for this project -> Click on the Create button.

If the above steps are followed, the following output will appear in Visual Studio.

Output :

undefined

  1. A project named DemoApplication will be created in Visual Studio. This project will include all the artifacts needed to run the console application.
  2. The Main program named Program.cs is a default code file that is created when a new app is created in Visual Studio. The Main program named Program.cs is a default code file (i.e. Hello World program) that is created when a new application is created within Visual Studio.

First, there should be modules included in the program with the ‘using’ keyword e.g. here we have “using System” included by default. These modules are needed so that any application .Net works properly. Then we have Namespace, Namespaces serve to organize classes, structs, interfaces, enums and delegates logically. Namespaces in C# can be nested. This means that a namespace can also contain other namespaces. Each application belongs to one class. C# is an object-oriented language, and therefore the entire code must be defined in a standalone module called "Class". The 'Main' function is a special function that is automatically invoked when a console application runs. The Console class is available in .Net that allows you to work with console apps. Here, we use a built-in method called "WriteLine" to write the string "Hello World" in the console.

Step 3: Execute your .Net code. To execute any program, you must click the Start button in Visual Studio. If the above code is entered correctly and the program is successfully executed, the following output appears.

Output :

undefined

From the output, you can see that the "Hello World" string is displayed correctly.

So, we now understand that a console application can be run at the command prompt on a Windows machine and the Console.WriteLine method enables you to write content to the console.

Data Types 

Data types are used to create values that are used within an application. Let’s try data types in our current project. For each example, only modify the main function of our file Program.cs.

  1. Integer: Integer can hold values of whole numbers like 10, 20 or 30. For C#, the data type is referred to by the keyword Int32. We can mend our code to the below code.

undefined

we have assigned an Integer value to the variable and we display it accordingly. The output will be 30 as it was assigned to the ‘num’ variable of Int32 data type which was used in the WriteLine function.

2. Double: A double data type is used for working with decimals (e.g.: 24.24, 32.02, etc). To create a variable with the double data type, just change the declaration of the above code with :

double num=24.03;

 3. Boolean: A Boolean data type is used to function with Boolean values of true and false. To create a variable with the Boolean data type, just change the declaration of the above code with :

Boolean status=true;

And also change the parameter inside the WriteLine function from ‘num’ to ‘status’.

4. String: A string data type is used for working with string(i.e. the combination of different characters) values. To create a variable with String data type, just change the declaration of the above code with :

String msg= “Hello”;

And also change the parameter inside the WriteLine function from ‘status’ to ‘msg’.

Variables and Operators 

Variable - Variable is a location in the memory which has a unique name and a value associated with it. The syntax to declare a variable and initialize a value to it is as follows: 

<data_type> <variable_name> = <value>;

Example - int a = 15;

  • Static variable - A field with the static modifier is known as the static variable. The default value of the variable’s data type is the initial value of the static variable. It comes into existence even before the static constructor is executed.

Example - public static int st_var;

  • Instance variable - The instance variable exists when the user creates a new instance of the class. Its initial value is the default value of the variable’s data type.

Example -

class marks 
{
int marks1;
Int marks2;
}
  • Local variable - A local variable is declared by the local variable declaration which can be a block of code, conditional statements etc. Its scope is the part of the program where it is declared.

Operators - Operators are one or more characters that are used to perform certain calculations on the variables (operands). There are six different types of operators, and they are as follows-

  1. Arithmetic operators
  2. Assignment operators
  3. Unary operators
  4. Comparison operators
  5. Logical operators
  6. Bitwise operators

Lets us discuss each of these in brief -

Arithmetic operators: It is used to perform the arithmetic operations on the variables. 

undefined

Arithmetic assignment operators: These are used to assign the resulting value to anyone variable after performing arithmetic operations on the variables. 

undefined

Unary operators: These are used to increment or decrement the value of the variable by a value of 1. 

undefined

Comparison operators: These are used to compare the value of two variables and then perform actions based on the results. 

undefined

Logical operators: These are used to evaluate the expressions and then return boolean values, i.e., true or false. 

undefined

Bitwise operators: These are the operators that are used to perform the operations on the values at the bit level. 

undefined

Conditional Statements 

C# supports the common logical conditions of mathematics:

  • Less than: a<b
  • Less than or equal to: a<=b
  • Greater than: a>b
  • Greater than or equal to: a>=b
  • Equal to a==b
  • Not Equal to: a!=b

You may use these conditions to execute different actions for different decisions. C# includes conditional statements as follows:

1. if statement :

Use the if command to specify a C# code block to perform if a condition is True.

Syntax:

 if(condition)
{
//code block to run if the condition is True.
}

2. else  statement :

Use the else command to specify a C# code block to perform if a condition is False.

Syntax:

if(condition)
{
//code block to run if the condition is True.
}
else
{
//code block to run if the condition is False.
}

3. else if statement :

Use the else if command to specify a C# code block to perform if a condition is True and the former condition is False.

Syntax:

if(condition)
{
//code block to run if condition1 is True.
}
else if(condition)
{
//code block to run if condition1 is False and condition2 is True.

}

else
{
//code block to run if condition1 and condition1 both are False.
}

4. Shorthand if Else statement (aka Ternary Operator):

It may be used to replace several lines of code with a single line. It is often used to simply replace any other statement.

Syntax : (condition) ? (expression, if the condition is true) : (expression, if the condition is false)

Array

Arrays are used to store multiple values within a single variable, rather than declaring separate variables for every value. Square brackets are used for array declarations.

Syntax : (datatype)[ ] (variable name);

We can assign values to arrays while declaring variables, like as shown in the following :

String names[ ] = {“Chandler”, “Joey”, “Ross”};

You access an array element with reference to the index number(which starts with zero as other programming languages).

Console.WriteLine(names[0]) //output will be Chandler

Reassign an array element as follows :

names[2] = “Monica”; //it will replace “Ross” with “Monica”

We can also get the length of an array with a simple function as shown below:

Console.length(names.length); // output will be 3

Class and Object 

A class is like an object builder or a "blueprint" for the creation of objects. To construct a class, use the ‘class’ keyword. We have already used a class in our program named ‘program’. An object is created based on a class. Let’s understand objects better by creating one:

using System;
namespace DemoApplication
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Mobile myObj1 = new Mobile();
            Mobile myObj2 = new Mobile();
            Console.WriteLine(myObj1.color); // output will be red
            Console.WriteLine(myObj2.color); //output will be red
        }
    }
    class Mobile
    {
        public string color = "red"
    }
}

Here, we have created two objects “myObj1” and “myObj2” from the class “Mobile”. This “Mobile”  class has an attribute (aka Variable) of string data type assigned with “red”. The variable is accessed through the class objects named myObj1 and myObj2.

Access Modifiers 

Access modifiers or access specifiers in C# are the keywords used to set the visibility of a class property or class method. Access modifiers give or limit access so that other programs can or can not see the properties or methods of a class. Six types of access modifiers exist in C#:

  • Private
  • Public
  • Protected
  • Internal
  • Protected Internal
  • Private protected

Private: When a private access modifier is attached to a property or method, this means that it cannot be accessed through an external program.

Public: When the public access modifier is applied to a property or method, any external programs can access those members. You have seen the use of this access modifier in our last program example. If you remove the public modifier from the code you will see errors coming up in the code. The errors are because it is not accessible as it’s not public.

Protected: Where the protected access modifier is associated with a property or method, it means that these members can be accessed only by classes inherited from the current class.

Internal: Where an internal access modifier is associated with a property or method, those members are only accessible through an internal program, but not through an external program.

Constructor

C# Constructors are used to initialize class field values when their respective objects are created. A constructor is a method whose name is identical to that of the class. If a constructor is defined in a class, then it will provide the first method that is called during the creation of an object. The following key points are to be noted on construction methods:

1. The default access modifier for the constructor has to be made public.

2. There cannot be a return type for the constructor method.

Abstract Class 

An abstract class has a keyword “Abstract” with the class syntax and no objects can be created from an abstract class. It is designed for inheritance by subclasses that implement or override its method. In simple terms, it is for designing all such methods for all Inherited classes that must contain them and validate.

Interface

A C# interface is used with a class to define a contract that is an agreement on what the class will deliver to an application. The difference between Abstract class and Interface is that Abstract class can be fully, partially, or not implemented but Interface has to be fully implemented.

Collections 

C# collection types are designed to store, manage and handle similar data more efficiently. Data handling involves the addition, deletion, search and insertion of data into the collection. Collection types implement common features such as:

  • Adding and Inserting Items into the Collection
  • Removing Items from the Collection
  • Search, sort, search Items
  • Replace the elements
  • Copy and clone collections and items
  • Capacity and count of properties to identify collection capacity and number of items in the collection

ArrayList

The ArrayList collection looks the same as the Arrays data type in C#. The major difference is the dynamic nature of the Array List collection. For arrays, you need to define how many elements the array can contain when declaring the array. But in the case of the Array List collection, that doesn't have to be done first. Items may be added or deleted to the Array List collection at any time.

Windows Forms Application 

Here, we are not just making console applications anymore. Let’s start making some real-life looking desktop applications. A Windows application is intended to be run on a computer. We will use Windows Forms Application to create desktop applications. Below is one example of such an application where we will have to use controls from a collection of controls such as labels, text boxes, list boxes, and so on, which we will find in Toolbox.

The steps are as follows:

Step 1: Step one is to create a new project in Visual Studio. For this, once Visual Studio is launched, you should choose the “create a new project” option.

Step 2: The following step is to choose the project type as the “Windows Forms App”. You must include the name and location of your project. Click on the Next button, and select your Framework version. I have used .Net Core 3.1 for this project -> Click on the Create button.

If the above steps are followed correctly, this is the output you’ll get:

undefined

Now, Project has been created and it will contain a few things as default in solution Explorer:

  • Form.cs
  • Program.cs

Let’s open the designer file for Form.cs by the following steps:

  • Right-click on the Form.cs file name or file code.
  • Select “View Designer”.

You’ll have a blank Form to design, which you can resize as per your requirements. After resizing my form looks as shown in the following image:

undefined

Now we need to show some text in my form, to show text we need a label controller. To get a label controller Drag and Drop Label from the Toolbox Menu (Toolbox is left side of the screen) to the form. Select Properties from the right-click menu on the Label. On the Right Side of the Screen, we have Properties of the controller selected. Inside  Properties change the Text field from “label1” to “First Name” and press Enter. After these steps you should have  a label inside this form like the following image shown:

undefined

Now, just like Label, we should add a TextBox control. Resize the width of the textbox as per requirements. And rename the (Name) field for the textbox in properties as “FirstNameTB”.

undefined

Create one more label for Last Name and edit the text for it. And create a textbox for the Last name, maintain the width size and rename the (Name) field for the textbox in properties as “LastNameTB”. Add one more label in the form below the last name textbox, clear the text for it in properties and rename the (Name) field for the label as “welcomeLbl”. Add two buttons at the bottom of the form. Change the text field for one button as “Ok” and for the other as “Clear”. Change the (Name) for the button with text ok from “button1” to “okBtn” and for the button with text clear change it from “button2” to “clearBtn”.

undefined

Now, double-click on anywhere in the form away from any controls. You will be in an auto-generated function named “Form1_Load” in “Form1.cs”.

Inside Form1_load function, type the following code below:

            this.okBtn.Enabled = false;
            this.clearBtn.Enabled = false;

This will keep the buttons disabled to be clicked and trigger the function it has to operate. Again, double-click on textbox for the first name and again you’ll be in an auto-generated function named “FirstNameTB_TextChanged” in the form “Form1.cs”.

Inside FirstNameTB_TextChanged function, type the following:

            if (this.FirstNameTB.Text == "" && this.LastNameTB.Text == "")
            {
                this.okBtn.Enabled = false;
                this.clearBtn.Enabled = false;
            }
            else
            {
                this.okBtn.Enabled = true;
                this.clearBtn.Enabled = true;
            }

And Again, double-click on the textbox for the last name and again you’ll be in an auto-generated function named “LastNameTB_TextChanged” in the form “Form1.cs”.

Inside LastNameTB_TextChanged function, type the following:

            if (this.FirstNameTB.Text == "" && this.LastNameTB.Text == "")
            {
                this.okBtn.Enabled = false;
                this.clearBtn.Enabled = false;
            }
            else
            {
                this.okBtn.Enabled = true;
                this.clearBtn.Enabled = true;
            }

Now, double click on the ok button, “okBtn_Click” will be auto-generated, type the following code inside the function:

this.welcomeLbl.Text = "Hi, Mr. "+this.LastNameTB.Text+", "+this.FirstNameTB.Text;

Double-click on the clear button, “clearBtn_Click” will be auto-generated, type the following code inside the function:

            this.FirstNameTB.Text = "";
            this.LastNameTB.Text = "";
            this.welcomeLbl.Text = "";

Your Windows Application is ready to greet its users. To execute the code click on the green start button or use the keyboard shortcut (ctrl + F5).

The following image is the output look in starting:

undefined

Enter your first and last name and click on the ok button to let the application greet you. The Output should be like the following image below:

undefined

On clicking on the clear button, it will go back to the default state(i.e. With no text in textboxes and welcome label).

Conclusion

In conclusion, in this article, we have learned about C# and how to write programs in C# using variables, starting from every programmer’s first code - hello world program, to windows form applications. Thank you for choosing this article for starting with Dot Net and Dot Net core Framework in C# language. Any Suggestions or Corrections are welcome and will help us bring more topics for you. Happy Coding.