
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 -
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 :
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 :
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.
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;
Example - public static int st_var;
Example -
class marks
{
int marks1;
Int marks2;
}
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-
Lets us discuss each of these in brief -
Arithmetic operators: It is used to perform the arithmetic operations on the variables.
Arithmetic assignment operators: These are used to assign the resulting value to anyone variable after performing arithmetic operations on the variables.
Unary operators: These are used to increment or decrement the value of the variable by a value of 1.
Comparison operators: These are used to compare the value of two variables and then perform actions based on the results.
Logical operators: These are used to evaluate the expressions and then return boolean values, i.e., true or false.
Bitwise operators: These are the operators that are used to perform the operations on the values at the bit level.
Conditional Statements
C# supports the common logical conditions of mathematics:
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: 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:
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:
Now, Project has been created and it will contain a few things as default in solution Explorer:
Let’s open the designer file for Form.cs by the following steps:
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:
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:
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”.
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”.
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:
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:
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.