Variables In C#

Before moving to the core concept of variables in C# I want to introduce you to some basics of using visual studio. I am not going deeper into this as we are focusing on C#. There’s a solution explorer in the right side of visual studio which we can use to open certain files.

This tree contains our project and inside that, we have all our resources that are by default created by .NET framework as discussed earlier. By default project folder is located in Documents/Visual Studio/Projects but you can save wherever you want to. Now comes the variable part. We can store a value in a variable in C# to use that in various complex mathematical logics or many other things e.g. we will add two numbers.

using System;
namespace Helloworld {
   class Program {
      static void Main(String[] args) {
         int x = 6;
         int y = 5;
         int z = x+y;

The output of the program will be 11.

Here we are declaring two variable ‘x’ and ‘y’ with a datatype integer. Well, a data type is a type of value (e.g. integer, string, etc.) we want to store in that variable. And for x we put 6 and for y we put 5. Then we do a simple mathematical addition and stored the result in a third integer variable z. And at last, we printed out the value in the console. We can also store data directly from a user using Console.Readline() method. An example of using this method is given below. We will ask the user for their name and favourite superhero and return a customized string. Let’s see.

using System;
namespace SuperHero{
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Enter your name: ");
         string name = Console.ReadLine();
         Console.WriteLine("Enter your favourite superhero");
         string superName = Console.ReadLine();
         Console.WriteLine("Hello " + name + ". Your are assigned as sidekick of " +superName+".");


Here we are reading from user input and storing strings in variables with data type string. Finally, we are concatenating the strings to form a customized string. We can only add values of the same data type. We can’t add the string with integer or vice versa. We can only read string data type from the console in order to read integer we have to convert that entry in integer by using Convert.ToInt32()method. We will dive into the details of the method later on. Next, we will move to operators.

Leave a Reply

Your email address will not be published. Required fields are marked *