Assignment operators in C#- Learn about assignment operator in C# with example and easy explanation. Also, learn assignment operator combined with arithmetic operators in C# like +=, *= etc. with example.

= Assignment operator in C#

Assignment operator in C# program is used to assign a value to a variable.

For example,
int a = 10;
Also, value of one variable can be assigned to another variable. For example, if two variables are a and b, value of b can be assigned to a as

a = b; // right hand side value will be assigned to left hand variable.

Note that right hand side variable must be initialized, means, it must have some value.

public class Sample
    {

        public static void Main(String[] args)
        {
 
		int a = 10;
		int b ;
		// assign value of right variable to left	
		b = a;	
		
		Console.WriteLine("b =" + b);
        Console.WriteLine("a =" + a);
        }
    }

NOTE: Assignment (=) operator can be combined with other operators in C# language.

Examples below.

+= , -=, *=, /=

e.g.
if variable is int a =10;
then n += 5; will result into 15.

+= C# Example

n += 5; is same as n = n+5.

C# Code Example

public class Sample
    {

        public static void Main(String[] args)
        {
 
		int n = 10;
		
		n += 5; // same as n = n+5;
        Console.WriteLine("n =" + n);	
		}
    }

Output:

n =15

Similarly, others -=, *= and /= works

-= C# Example

note that n -= 5; is same as n=n-5;

public class Sample
    {

        public static void Main(String[] args) 
        {
 
		int n = 10;
		
		n -= 5; // same as n = n-5;		

        Console.WriteLine ("n =" + n);	
		}
    }

Output:
n =5

*= C# example:

n *= 5; is same as n=n*5;

C# Code example

public class Sample
    {

        public static void Main(String[] args) 
        {
 
		int n = 10;
		
		n *= 5; // same as n = n*5;		

        Console.WriteLine("n =" + n);	
		
        }
    }

Output:
n =50

/= C# Examples

n /= 5; is same as n=n/5;

C# Code example

public class Sample
    {

        public static void Main(String[] args) 
        {
 
		int n = 10;
		
		n /= 5; // same as n = n/5;		

        Console.WriteLine("n =" + n);	
		}
    }

Output:
n =2

%= C# Examples

n %= 5; is same as n=n%5;

C# Code example

public class Sample
    {

        public static void Main(String[] args) {
 
		int n = 10;
		
		n %= 5; // same as n = n%5;		

        Console.WriteLine("n =" + n);	
		
	}
    }

Output:
n =0

Related Posts