C# Language Fundamentals

There are following some fundamental concepts programmer should know before start programming in C#.

Let’s read c# language fundamentals:

  1. Variables: 

While executing a program, data is temporarily stored in memory. Variable is the name given to the memory location where data is stored. In C# variables are declared as below

<TYPE> <variable_name>;

In above syntax, a type is the data type of variable and variable_name is a name. It is necessary to declare variables before using it. From above syntax, we declare integer variable as below

int a;

One can also initialize the variable at the time of declaration as

int a=10;
  1. Constants & Literals:

 The constant value of constant can’t be changed during execution of a program. They are immutable objects in C#; their values are assigned at compile time. We can declare any built-in type constants like integer, float, or string. The fixed values which are assigned to constants are known as literals. Literals categorized as follows

  • Integer Literals:

Integral literal represents a number without any fractions. They can be any octal, decimal, or hexadecimal. The prefix is used to represents the base or radix like ‘0X’ or ‘0x’ for hexadecimal. The suffix u/U and l/L is used for unsigned and long. Below are some examples of integer literals

100   // Decimal Literal 
0xA10// Hexadecimal Literal 
11u//Unsigned Integer Literal
  • Floating Point Literals:

A Float-point literal has two parts, one is integer part and another one is the fractional part. They can be of type float or double. The suffix f/F is used to specify the float value and suffix d/D is used to specify the double value.

1.27//Float Literal 
1.23F//Float Literal 
3.3738 // Double Literal
  • Boolean Literals:

The boolean type literals take only two values that are true and false. They are of type bool.

IsWrong=true;
  • Character Literals:

 A character literal represents a single character. They are enclosed in single quotes linked’. They are of character type. A character literal specifies a plain character, an escape sequence (like ‘\b’) or universal character (‘\u01B’). In C# escape sequence is special characters with prefix backslash (\) and they have some special meaning. The following list represents escape sequences with their meanings

Escape Sequence Meaning
\\

It represents backslash.

\” It represents doublequote.
\’ It represents single quote.
\n It represents a new line.
\t It represents horizontal tab.
\v It represents vertical tab.
\? It represents the question mark.
\a It represents alert or bell.
\b It represents backspace.
\f It represents form feed.
\r It represents the carriage return.
\xhhh… It represents the hexadecimal number or one more digit.

Following is the example of escape sequence

using System;
namespace EscapeSequence 
{ 
  class Program 
  { 
    static void Main(string[] args) 
    { 
       Console.WriteLine("This is the example of \t Escape Sequences."); 
       Console.ReadLine(); 
    } 
  } 
}
The output of above program is This is the example ofEscape Sequences.
  • String Literals:

The string literal is a set of characters. String literals are enclosed in double quotes (“”) or @””. Defining Constants: Constants are declared using ‘const’ keyword. The constants are defined like variables with the data type and name, but it is mandatory to assign the value to the constant at the time of declaration. Following is syntax to define constants

const <TYPE> <name>=value;

further, we will learn how to use constants with the help of the following example

using System;
namespace ConstantDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      const float PI = 3.14f;     // Constant PI declaration
      Console.WriteLine("The value of PI is: "+PI);
      Console.ReadLine();
    }
  }
}
The output of above program is  The value of PI is: 3.14 
  1. Operators:
Recommended Post   C# String Manipulation 

C# language provides various operators which help the programmers to perform the mathematical calculation, logical manipulations etc. Operators in C# categorized as below

  • Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations like addition, subtraction etc. C# support following arithmetic operators

Operator

Description
+ Addition of two operands
Subtract the second operand from first operand
* Multiplication of two operands
/ Divide the first operand by the second operand
% Remainder or modulo of division of two operands
++ Increment value of operand by one

Decrement value of operand by one

We see working with these operators with the help of below program

using System;
namespace ArithmeticOperation
{
  class Program 
  { 
    static void Main(string[] args)
    { 
      int num1 = 2; 
      int num2 = 7;
      int result; 
      //Addition 
      result = num1 + num2; 
      Console.WriteLine("Result of num1 + num2 is "+result);
      //Subtraction
      result = num1 - num2; 
      Console.WriteLine("Result of num1 - num1 is " + result);
      //Multiplication 
      result = num1 * num2; 
      Console.WriteLine("Result of num1 * num2 is " + result); 
      //Division 
      result = num1 / num2; 
      Console.WriteLine("Result of num1 / num2 is " + result); 
      //Remainder 
      result = num1 % num2; 
      Console.WriteLine("Result of num1 % num2 is " + result); 
      num1++; 
      Console.WriteLine("Result of num1++ is " + num1); 
      //Decerment
      num2--; 
      Console.WriteLine("Result of num2-- is " + num2);
      //Incerment 
      Console.ReadLine();
    }
  }
}

The output of above program is as below

Result of num1 + num2 is 9 
Result of num1 - num2 is -5  
Result of num1 * num2 is 14 
Result of num1 / num2 is 0  
Result of num1 % num2 is 2 
Result of num1++ is 3  
Result of num2-- is 6

Prefix and Postfix increment and decrement operator: We can use ++ and — as prefix or postfix operator. Suppose ++ operator is used as prefix like ++a. The value of num1 is incremented then it returns the value. Suppose ++ is used as postfix like num1++. The value of num1 is returned first then, it is incremented. The same thing is applicable for – operator. Let’s check this with program

using System;
namespace PrefixPostfixDemo
{ 
  class Program
  {  
    static void Main(string[] args)
    {
      int a = 2; 
      int b = 2; 
      Console.WriteLine(a++);      //Postfix increment 
      Console.WriteLine(++b);     //Prefix increment
      Console.ReadLine();
    }
  }
}
The output of above program is as below
2
3
  • Relational Operators:

Relational operators are used to check conditions. These operator returns a Boolean value (true or false).

Operator Description
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Now we will learn  to work with these operators with the help of below program

using System;
namespace RelationalOperators
{
  class Program
  {
    static void Main(string[] args)
    {
      int number1 = 10;
      int number2 = 20;
      if (number1 == number2)
      {
        Console.WriteLine("number1 is equal to number2");
      }
      else
      {
        Console.WriteLine("number1 is not equal to number2");
      }
      if (number1 < number2)
      {
        Console.WriteLine("number1 is less than number2");
      }
      else
      {
        Console.WriteLine("num1 is not less than number2");
      }
      if (number1 > number2)
      {
        Console.WriteLine("number1 is greater than number2");
      }
      else
      {
        Console.WriteLine("number1 is not greater than number2");
      }
      Console.ReadLine();
    }
  }
}
The output of above program is as below
number1 is not equal to number2
number1 is less than number2
number1 is not greater than number2
  • Logical Operators:

Logical operators are works with bool type of operands and return the result of type bool.

Recommended Post   C# Tutorial
Operator Description
|| OR
&& AND
! NOT

Let’s us use of these operators with the help of below program

using System;
namespace LogicalOperators
{
   class Program
   {
     static void Main(string[] args)
     {
       bool b1 = true;
       bool b2 = false;
       if (b1 && b2)
       {
         Console.WriteLine("Result of b1 && b2 is true.");
       }
       else
       {
         Console.WriteLine("Result of b1 && b2 is false.");
       }
       if (b1 || b2)
       {
         Console.WriteLine("Result of b1 || b2 is true.");
       }
       else
       {
         Console.WriteLine("Result of b1 || b2 is false.");
       }
       if (!(b2))
       {
         Console.WriteLine("Result of  !(b2) is true.");
       }
       else
       {
         Console.WriteLine("Result of  !(b2) is false.");
       }
       Console.ReadLine();
     }
   }
}

The output of above program is as below

Result of b1 && b2 is false.
The result of b1 || b2 is true.
The result of !(b2) is true.
  • Bitwise Operators:

Bitwise operators directly work on the bits of their operands. They work with only integer operands. They cannot be used with bool, float, or double type operands.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift right
>> Shift left
~ One’s complement

We see working of these operators with the help of below program

using System;
namespace BitwiseOperators
{
  class Program
  {
    static void Main(string[] args)
    {
      int a = 50;            // 50 = 0011 0010
      int b = 23;            // 23 = 0001 0111
      int result = 0;
      result = a & b;             // 18 = 0001 0010
      Console.WriteLine("Result of a & b is "+ result);
      result = a | b;             // 55 = 0011 0111
      Console.WriteLine("Result of a | b is "+ result);
      result = a ^ b;             // 37 = 0010 0101
      Console.WriteLine("Result of a ^ b is "+ result);
      result = ~a;                //-51 = 1100 1101
      Console.WriteLine("Result of ~a is "+ result);
      result = a << 2;      // 200 = 1100 1000
      Console.WriteLine("Result of a<<2 is "+ result);
      result = a >> 2;      // 12 = 0000 1100
      Console.WriteLine("Result of a>>2 is "+result);
      Console.ReadLine();
    }
  }
}

The output of above program is as below

Result of a & b is 18
Result of a | b is 55
Result of a ^ b is 37
Result of ~a is -51
Result of a<<2 is 200
Result of a>>2 is 12
  • Assignment Operators:

The assignment operators are used to assign values to variables. C# Support following types of assignment operators.

Operator Description
= Simple assignment
+= Additive assignment
-= Subtractive assignment
*= Multiplicative assignment
/= Division assignment
%= Modulo assignment

Example:

using System
namespace AssignmentOperators
{
  class Program
  { 
    static void Main(string[] args)
    {
      int a =100;
      int b;
      b = a;
      Console.WriteLine("Result of b=a is "+ b);
      b += a;
      Console.WriteLine("Result of b += a is " + b);
      b -= a;
      Console.WriteLine("Result of b -= a is "+ b);
      b *= a;
      Console.WriteLine("Result of b *= a is "+ b);
      b /= a;
      Console.WriteLine("Result of b /= a is "+ b);
      b = 210;
      b %= a;
      Console.WriteLine("Result of b %= a is "+ b);
      b <<= 2;
      Console.WriteLine("Result of b <<= a is "+ b);
      b >>= 2;
      Console.WriteLine("Result of b >>= a is "+ b);
      b &= 2;
      Console.WriteLine("Result of b &= a is "+ b);
      b ^= 2;
      Console.WriteLine("Result of b ^= a is "+ b);
      b |= 2;
      Console.WriteLine("Result of b |= a is "+ b);
      Console.ReadLine();
    }
  }
}

The output of above program is as below

Result of b=a is 100
Result of b += a is 200
Result of b -= a is 100
Result of b *= a is 10000
Result of b /= a is 100
Result of b %= a is 100
Result of b <<= a is 40
Result of b >>=a is 10
Result of b &= a is 2
Result of b ^=a is 0
Result of b |=a is 2
  • Other  Operators

C# also supports some other operators as follows.

Operator Description
. Member access operator used to access members of class
() Cast operator
?: Conditional or ternary operator
sizeof() Used to determine size of data type
Recommended Post   C# Classes & Objects 

The conditional operator is mostly used to replace if-else statement in the program. It takes three operands as below

Exp1 ? Exp2: Exp3

In above statement, Exp1 is the expression which returns bool value (true/ false), and Exp2 and Exp3 are statements to be executed depending upon the result. If Exp1 returns to true then Exp2 is executed and value of Exp2 is returned else Exp3 is executed and value of Exp3 is returned. Let’s see example of sizeof() and conditional operator

using System;
namespace OtherOperators
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Result of sizeof(int) is " + sizeof(int));
      Console.WriteLine("Result of sizeof(double) is " + sizeof(double));
      int a = 10;
      int b = 20;
      int c;
      c = a == b ? 20 : 30;
      Console.WriteLine("Value of c is "+ c);
      Console.ReadLine();
    }
  }
}
The output of above program is as below
Result of sizeof(int) is 4
Result of sizeof(double) is 8
Value of c is 30
  1. Namespaces: 

In C# namespace is the logical collection which may contain classes, interfaces, structs, enums, delegates etc. Namespace helps to organize a large amount of code. The .Net framework class library (FCL) is also divided into several namespaces like System namespace. With help of namespace, we can declare classes with the same name but in a different namespace. Defining a Namespace: The syntax for defining namespace is as below

namespace Name
{
// Code of Classes, interfaces, structs, enums etc.
}

Once the namespace is defined you can use classes or interfaces in the namespace using dot operator (.). See the following example

using System;
namespace DemoNamespace1
{
  public class Demo
  {
    public void Display()
    {
      Console.WriteLine("This is defined in DemoNamespace1.");
    }
  }
}
namespace DemoNamespace2
{
   public class Demo
   {
     public void Display()
     {
       Console.WriteLine("This is defined in DemoNamespace2.");
     }
   }
}
namespace NamespaceDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      DemoNamespace1.Demo D1 = new DemoNamespace1.Demo();
      DemoNamespace2.Demo D2 = new DemoNamespace2.Demo();
      D1.Display();
      D2.Display();
      Console.ReadLine();
    }
  }
}

The output of above program is

This is defined in DemoNamespace1.
This is defined in DemoNamespace2.

using Keyword: In above example to access classes in namespace we use namespace and dot operator, we can eliminate this work with the help of ‘using’ keyword. Let’s rewrite the above program as below

using System;
using DemoNamespace1;
using DemoNamespace2;
namespace DemoNamespace1
{
  public class Demo
  {
    public void Display()
    {
      Console.WriteLine("This is defined in DemoNamespace1.");
    }
  }
}
namespace DemoNamespace2
{
  public class Demo
  {
    public void Display()
    {
      Console.WriteLine("This is defined in DemoNamespace2.");
    }
  }
}
namespace NamespaceDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      Demo D1 = new Demo();
      Demo D2 = new Demo();
      D1.Display();
      D2.Display();
      Console.ReadLine();
    }
  }
}
The output of above program is:
This is defined in DemoNamespace1.
This is defined in DemoNamespace2.
  1. Classes & objects: Classes in C# are defined using following syntax
class Class_Name
{
  //Class members
}

In above syntax class is the keyword used to declare class and Class_name is any identifier name given to the class. Once class is defined we create objects of that class using ‘new’ keyword like below

Class_Name obj=new Class_name();

To access class member dot operator is used. The following program gives the idea about class and objects

using System;
namespace ClassDemo
{
  class Demo
  {
    public void Display()
    {
      Console.WriteLine("This is example of defining class.");
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      Demo D = new Demo();   // Object of class D is created
      D.Display();           //Accessing member function using dot operator
      Console.ReadLine();
    }
  }
}

The output of above program is: This is example of defining class.

Content Protection by DMCA.com