top
upGrad KnowledgeHut SkillFest Sale!

Search

C# Tutorial

In this lesson, we will learn how to work with variables and constants in C#. Let us first begin with variables:Variables in C#Variables are the names used for the storage areas that are manipulated by the programs to obtain various results. There are different types of variables such as integral, floating-point, boolean, character etc. The variable type determines the size and layout of the variable memory.Variable Definition and InitializationA variable can be defined using the following syntax:DataType VariableList ;Here, “DataType” can be any valid C# data type such as int, float, double, char, bool, etc.         “VariableList” may contain one or more variable names separated by commas.Variables can be initialized using the assignment operator with the variable name to its left and the value assigned to its right. This is shown as follows:VariableName = Value;Here, “VariableName” is the name of the variable.         “Value” is the value assigned to the variable.Variable initialization can also be done at the time of variable declaration. The syntax for that is as follows:DataType VariableName = Value;Here, “DataType” can be any valid C# data type such as int, float, double, char, bool etc.         “VariableName” is the name of the variable.         “Value” is the value assigned to the variable.A C# program that demonstrates variable definition and initialization is as follows:Source Code: Program to work with variables in C#using System; namespace Demo {   public class Example {      public static void Main(string[] args) {      int a =10;      int b;      b=15;      Console.WriteLine("Value of a is {0}",a);      Console.WriteLine("Value of b is {0}",b);      }   } }The output of the above program is as follows:Value of a is 10 Value of b is 15Variable Naming ConventionsThe variable naming conventions in C# are as follows:A variable should only start with an alphabet or underscore. It should not start with a digit.A variable may contain alphabets, digits as well as underscore.There can be no whitespace in a variable name.A variable name cannot contain any keywords such as int, const, switch etc.A list of valid and invalid variable names is as follows:int var;                             // Valid int _var;                           // Valid int var1;                           // Valid int name_var_1;              // Valid int 10;                              // Invalid int 10val;                         // Invalid int name var 1;                // Invalid int switch;                        // InvalidReading input from ConsoleThe function ReadLine() in the Console class in the System namespace is used to accept input from the user and store it into a variable. This can be done by writing Console.ReadLine() to accept the user input. However, this accepts the input in string format and so Convert.ToInt32() is used in the case of int data types to convert the input to int.A program to demonstrate this is as follows:Source Code: Program to read input from Console in C#using System; namespace Demo { public class Example {  public static void Main(string[] args) {   int val;   val = Convert.ToInt32(Console.ReadLine());   Console.WriteLine("Value of val is {0}", val);  } } }The output of the above program for input value 5 is:Value of val is 5Constants in C#Constants in a program are fixed values that cannot be altered once they are given. They can be an integer constant, floating constant, character constant or string literal.Constants can be defined using the const keyword.The syntax is given as follows:const DataType ConstantName = value; Here, “const” is the keyword          “DataType” can be any valid C# data type such as int, float, double, char, bool etc.          “ConstantName” is the name given to the constant.          “value” is the value assigned to the constantA program that demonstrates the constant data type is as follows:Source Code: Program to implement constant data types in C#using System;   namespace Constants {    public class Example {       public static void Main(string[] args) {             const double pi = 3.14159;   // constant declaration           double r;                  r = Convert.ToDouble(Console.ReadLine());                       double area = pi * r * r;          double circumference = 2 * pi * r;             Console.WriteLine("Area of circle is: {0}",area);          Console.WriteLine("Circumference of circle is: {0}",circumference);                }    } }The output of the above program is as follows:Area of circle is: 78.53975 Circumference of circle is: 31.4159
logo

C# Tutorial

Variables and Constants in C#

In this lesson, we will learn how to work with variables and constants in C#. Let us first begin with variables:

Variables in C#

Variables are the names used for the storage areas that are manipulated by the programs to obtain various results. There are different types of variables such as integral, floating-point, boolean, character etc. The variable type determines the size and layout of the variable memory.

Variable Definition and Initialization

A variable can be defined using the following syntax:

DataType VariableList ;

Here, “DataType” can be any valid C# data type such as int, float, double, char, bool, etc.
         “VariableList” may contain one or more variable names separated by commas.

Variables can be initialized using the assignment operator with the variable name to its left and the value assigned to its right. This is shown as follows:

VariableName = Value;

Here, “VariableName” is the name of the variable.

         “Value” is the value assigned to the variable.

Variable initialization can also be done at the time of variable declaration. The syntax for that is as follows:

DataType VariableName = Value;

Here, “DataType” can be any valid C# data type such as int, float, double, char, bool etc.
         “VariableName” is the name of the variable.

         “Value” is the value assigned to the variable.

A C# program that demonstrates variable definition and initialization is as follows:

Source Code: Program to work with variables in C#

using System;
namespace Demo {
  public class Example {
     public static void Main(string[] args) {
     int a =10;
     int b;
     b=15;
     Console.WriteLine("Value of a is {0}",a);
     Console.WriteLine("Value of b is {0}",b);
     }
  }
}

The output of the above program is as follows:

Value of a is 10
Value of b is 15

Variable Naming Conventions

The variable naming conventions in C# are as follows:

  1. A variable should only start with an alphabet or underscore. It should not start with a digit.
  2. A variable may contain alphabets, digits as well as underscore.
  3. There can be no whitespace in a variable name.
  4. A variable name cannot contain any keywords such as int, const, switch etc.

A list of valid and invalid variable names is as follows:

int var;                             // Valid
int _var;                           // Valid
int var1;                           // Valid
int name_var_1;              // Valid
int 10;                              // Invalid
int 10val;                         // Invalid
int name var 1;                // Invalid
int switch;                        // Invalid

Reading input from Console

The function ReadLine() in the Console class in the System namespace is used to accept input from the user and store it into a variable. This can be done by writing Console.ReadLine() to accept the user input. However, this accepts the input in string format and so Convert.ToInt32() is used in the case of int data types to convert the input to int.

A program to demonstrate this is as follows:

Source Code: Program to read input from Console in C#

using System;
namespace Demo {
public class Example {
 public static void Main(string[] args) {
  int val;
  val = Convert.ToInt32(Console.ReadLine());
  Console.WriteLine("Value of val is {0}", val);
 }
}
}

The output of the above program for input value 5 is:

Value of val is 5

Constants in C#

Constants in a program are fixed values that cannot be altered once they are given. They can be an integer constant, floating constant, character constant or string literal.

Constants can be defined using the const keyword.

The syntax is given as follows:

const DataType ConstantName = value; 

Here, “const” is the keyword
          “DataType” can be any valid C# data type such as int, float, double, char, bool etc.
          “ConstantName” is the name given to the constant.

          “value” is the value assigned to the constant

A program that demonstrates the constant data type is as follows:

Source Code: Program to implement constant data types in C#

using System;
 
namespace Constants {
   public class Example {
      public static void Main(string[] args) {
  
         const double pi = 3.14159;   // constant declaration 
         double r;
       
         r = Convert.ToDouble(Console.ReadLine());
            
         double area = pi * r * r;
         double circumference = 2 * pi * r;
  
         Console.WriteLine("Area of circle is: {0}",area);
         Console.WriteLine("Circumference of circle is: {0}",circumference);
        
      }
   }
}

The output of the above program is as follows:

Area of circle is: 78.53975
Circumference of circle is: 31.4159

Leave a Reply

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

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial