Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Variables in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A variable in any programming language is nothing but a name given to some storage area that our programs can modify or manipulate. In Variables in C#, we declare them before using them in the program. All Variables in C# have a specific data type, which determines the layout and size of the variable's memory, the range of data it can store within that memory, and the operations that we can apply to the variable.

This article will focus on different types of Variables in C#, their default values, and ranges.

Recommended Topic, Palindrome in C# and Ienumerable vs Iqueryable.

Variables in C#

Variables are the basic unit of storage in any program. The value stored in variables can be modified during program execution. 

The primary value types provided for Variables in C# can be categorized as follows:-

Types

Description

int It stores integers without decimals, such as 120 or -120.
double It stores floating-point numbers with decimal values, such as 9.99 or -9.99.
char It stores single characters, like 'A' or 'b'. A single-quote pair surround char values.
string It stores multiple characters, such as "Hello World". A double quote surrounds a String value.
bool It stores values with two states: false or true.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Defining Variables in C#

The syntax for defining variable in C# is −

<data_type> <variable_list>;

 

Here, data_type is a valid C# data type including int, char, double, float, or any user-defined data type, and the variable_list may consist of one or more identifiers name separated by commas. For example,

int a, b, c;
char ch;
float f, amount;
double d;

Initializing Variables in C#

We can initialize Variables in C# with an equal sign followed by any valid constant expression. The general form for initialization a variable in C# is −

variable_name = value;          /* Here variable_name is defined earlier. */
<data_type> <variable_name> = value;           /* Initializing while defining */

 

Now let's see an example of initializing a variable.

int d = 2, f = 3;                /* Initializing d and f */
byte z = 222;         /* Initializes z */
double pi = 3.1415;     /* Declares an approximation of pi */
char c = 'C';    

Naming conventions for Variables in C#

The naming convention for declaring a variable in C# is listed below:

  • A variable name should be unique.
  • A variable name can only contain digits, letters, and the underscore "_".
  • A variable name must start with a letter.
  • A variable name is case-sensitive; n and N are considered as two different names.
  • A variable name cannot contain any reserved keywords (e.g. enum, break, case, etc.). We must prefix @ before keyword if we want to use reserve keywords as identifiers.

Constants

If we declare a variable using the keyword "const", it is known as a constant variable. We can't modify these constant variables once after their declaration, so we must initialize it at the time of declaration only.

The const keyword is often useful when we want any variable always to store the same value so that others (or ourselves) won't mess up with our code. For example, we often refer to PI(3.14159…) as a constant variable. Let's see this example below:

const int myNum = 25;
myNum = 22;                   // error

 

Note: We cannot declare a constant variable without assigning a value. If we do so, an error will occur: "A const field requires a value to be provided".

Differences between Constants and Variables

The major differences between constants and variables are listed below in the table:

Variable

Constant

We declare a variable with the following syntax: <data_type> variable_name We declare a variable with the following syntax: const <data_type> variable_name
We can modify its value even after their declaration. We can't modify its value even after their declaration.
We can declare a variable without assigning a value to it. We can't declare a constant without assigning a value to it.

Read-Only Variables

In C#, we can use the readonly keyword to define a readonly variable. The readonly keyword shows that we can assign a value to the variable only while declaring the variable or in any constructor of the class. Let's see an example of readonly variable below:

using System;
 
class Codingninjas{
 
    // Read-only variables
    public readonly int myvar1;
    public readonly int myvar2;
 
    // Values of the readonly variables are assigned in constructor


    public Codingninjas(int b, int c){
 
            myvar1 = b;
            myvar2 = c;
    }
 
    // Main method
    static public void Main()
    {
             Codingninjas obj1 = new Codingninjas(100, 200);
    }
}

 

In the above code, we have declared read-only variables and then assigned values to them using a constructor.

Global variables

In C#, we can't define a true global variable that any class can access. But we can implement this feature by using a static class as follows:

public static class GlobalVars {
    public const Int32 Int_Var= 512; // Unmodifiable
    public static String str_var= "String Variable"; // Modifiable
    public static readonly String str_var2 = "Readonly variable"; // Unmodifiable
}

 

Now, we can retrieve the defined values anywhere in our code (provided that it's part of one namespace). It is called global namespace alias.

Let's see how we can access these global variables anywhere in our code:

String code = Globals.str_var2 + value.ToString();

FAQs

  1. What are Instance Variables in c#?
    Instance variables are non-static variables declared within a class but outside the methods, constructors or blocks. Unlike local variables, we may use access specifiers, for instance, variables.
     
  2. How to cast variable types in C#?
    Casting is performed by placing a variable type to which we wish to convert before the variable's name we wish to convert from. For example, to convert any long value to an int: myInteger = (int) myLong.
     
  3. What are the differences between the instance variable & the static variable?
    An Instance variable is created when an object is created by using the 'new' keyword and destroyed when the object is destroyed. A Static variable is created when the program starts and is destroyed with the program's end.
     
  4. What are the local variables in C#?
    We use a local variable if the variable's scope is within the method in which we declare it. We can use them only by the statements that are inside that function or block of code. 

    For example,
using System;
public class Program {
   public static void Main() {
      int localVar = 1;
      // local variable
      Console.WriteLine("Value:"+ localVar);
   }
}

Key Takeaways

In this article, we have extensively discussed Variables in C#, initialization, and naming conventions. We also learned about different types of Variables in C#.

We hope that this blog has helped you enhance your knowledge regarding Variables in C# and if you would like to learn more, check out our articles on Introduction To C#C# Comments, and Decision Making in C#. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Variables in C#
3.
Defining Variables in C#
4.
Initializing Variables in C#
5.
Naming conventions for Variables in C#
6.
Constants
7.
Differences between Constants and Variables
8.
Read-Only Variables
9.
Global variables
10.
FAQs
11.
Key Takeaways