Implicitly Typed Local Variables in C#

We usually specify the data type of the variable while declaring it like int age; string name; etc. This is known as explicitly typed variables.

But sometimes, we need to create a variable that can hold any variable of any data type. We can do this using var keyword. This is known as implicitly typed variables. The var keyword can be used in place of specifying a specific data type such as int, string etc. When you do so, the compiler will automatically infer the underlying data type based on the initial value used to initialize the local data point.

Below is a sample code:

var myInt = 1234;
var myBool = true;
var myStr = "Hello";

Console.WriteLine("Value of myInt is: " + myInt + " and type of myInt is: " + myInt.GetType().Name);
Console.WriteLine("Value of myBool is: " + myBool + " and type of myBool is: " + myBool.GetType().Name);
Console.WriteLine("Value of myStr is: " + myStr + " and type of myStr is: " + myStr.GetType().Name);

Below is the output of the above code:

Restrictions on implicit typed local variables

    • Implicit typing applies only to local variables in a method or property scope.
    • It is illegal to use var keyword to define return values, parameters or field values of a custom type.
      For example, below are invalid usage of var keyword:
      class varUsage
      {
      // Error: var cannot be used as field data
      private var age=100;
      // Error: var cannot be used as a return value or parameter type
      public var Add(var a, var b){}
      }
    • Local variables declared with the var keyword must be assigned an initial value at the time of their declaration. We cannot assign null value to varExample:// Error: Must assign an initial value to var variables
      var data;// Error: Must assign value at the time of declaration
      var data;
      data = “Hello”;// Error: Can’t assign null
      var data = null;

      // No error as this is a reference type;
      var car = new Vehicle();
      car = null;

      // Below code is also fine
      var data = “hello”;
      var data1 = data;

    • It is allowed to return an implicitly typed local variable to the caller, provided the method return type is the same as of var-defined data type.Example:
      static int GetValue()
      {
      var value=9;
      return value;
      }

    Implicit typed data is strongly typed data

    Implicit typed data effects only at compile time. After that, that variable is treated as if it was declared with that data type. You cannot assign a value of different data type to that variable, even at later point of time. It will result in compile time error.
    Example:
    static void GetValue()
    {
    var str = “Hello World”;
    str = “Hiiii”;

    // Error: Cannot implicitly convert type ’int’ to ‘string’
    str = 1234;
    }

Arrays in C#

Arrays are a set of items of same data types which are accessed using numerical index. This index starts with 0. Arrays have pre-specified length. For example, an array of 5 integers, an array of 7 strings etc.

Below is the sample code for array:

static void Main(string[] args)
{
    // Declaring array. 3 is the total number of elements in the array.
    int[] codes = new int[3];

    // Filling array
    codes[0] = 1234;
    codes[1] = 2222;
    codes[2] = 9876;

    // Array Declaration and Initialization. 
    // You need not to specify the size of array in below case. 
    string[] countries = new string[5] { "India","Nepal","China","USA","Mexico"};

    // Accessing array elements using indexes
    for(int i=0;i<codes.Length;i++)
    {
        Console.WriteLine(codes[i]);
    }
    Console.WriteLine();
    foreach (string cntry in countries)
        Console.WriteLine(cntry);

    Console.ReadLine();
}

Below is the output of the above code:

You will get compiler error in the below code “An array initializer of length ‘2’ is expected”, as defined length of array is less as compared to the number of items assigned n it.

string[] countries = new string[2] { "India","Nepal","China","USA","Mexico"};

The value of e^x is 1+x+(x^2)/2+(x^3/3) …… (x^n/n) using C#

The value of e^x is 1+x+(x^2)/2+(x^3/3) …… (x^n/n). We are taking values of x and n from user.
Below is the code for the above problem in C#:

class Program
{
    static void Main(string[] args)
    {
            Console.WriteLine("The value of e^x is 1+x+(x^2)/2+(x^3/3) ...... (x^n/n) ");
            Console.WriteLine("Enter the value of x: ");
            int x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter the value of n: ");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Sum is: " + Exp(x,n));
            Console.ReadLine();
     }
     static double Exp(int x, int n)
     {
            double sum = 1;
            for (int j = 1; j <= n; j++)
            {
                sum = sum + (Math.Pow(x, j) / j);
            }
            return sum;
      }
}

Below is the output of above code:

Method Overloading

In Method Overloading, we define multiple methods with same name, but different parameters like number of parameters, different data types of parameters.

Below is a sample code:

class Program
{
    static void Main(string[] args)
    {
        AddNumbers(3, 4);
        AddNumbers(1.5, 6.7);
        AddNumbers(1256564, 3466757);
        AddNumbers("Hello", "3466757");
    }
    static void AddNumbers(int a, int b)
    { Console.WriteLine("{0} + {1} = {2}", a,b,a+b); }
        
    static void AddNumbers(double a, double b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }

    static void AddNumbers(long a, long b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }

    static void AddNumbers(string a, string b)
    { Console.WriteLine("{0} + {1} = {2}", a, b, a + b); }
}

Below is the output of above code:

Parameter Modifier (out, ref, params)

Parameter Modifiers are used to control how parameters are passed to the methods. There are three types of parameter modifiers: ref, out and params. If there is no modifier mentioned, it means it is passed value meaning the called method receives a copy of the original data. We cannot define overloaded method if it differs from another method only on out and ref.

out modifier
Output parameters must be assigned by the method being called, hence are passed by reference. We use out keyword to define output parameters.

class Program
{
     static void Main(string[] args)
     {
          int resultOut;
          AddNumbersOut(10, 20, out resultOut);
          Console.WriteLine("Value of result using out parameter: " + resultOut);
     }
     static void AddNumbersOut(int num1, int num2, out int sum)
     {
          sum = num1 + num2;
     }
}

If the called method fails to assign output parameters, a compiler error is raised.

ref modifier
The value is initially assigned by the caller and may be optionally reassigned by the called method. Data is passed by reference. No compiler error is generated if the called method fails to assign a ref parameter.

class Program
{
      static void Main(string[] args)
      {
          int resultRef=0;
          AddNumbersRef(10, 20, ref resultRef);
          Console.WriteLine("Value of result using out parameter: " + resultRef);
      }
      static void AddNumbersRef(int num1, int num2, ref int sum)
      {
          sum = num1 + num2;
      }
}

If caller method fails to assign the ref variable before passing it to the method, a compiler error is generated.

params modifier
This modifier allows you to send in a variable a number of arguments as a single logical parameter. A method can have a single params modifier, and it must be the final parameter of the method. Arguments marked with the params keyword can be processed if the caller sends in a strongly typed array or a comma-delimited list of items. These arguments are of same data type.

To understand this, lets create a method which can take any number of arguments and return the sum of those values.

class Program
{
     static void Main(string[] args)
     {
          int resultParams;
          AddNumbersParams(out resultParams, 10,20,30,40,50);
          Console.WriteLine("Value of result using out parameter: " + resultParams);}
     }
     static void AddNumbersParams(out int sum, params int[] nums)
     {
          sum=0;
          if (nums.Length == 0)
              sum = 0;
          for(int i=0;i<nums.Length;i++)
          {
              sum = sum + nums[i];
          }
     }
}

If you do not declare params as the last parameter, it will raise a compiler error.

Custom Methods and Parameters in C#

There are lots of in-built methods in C# that have their own functionality like Main() method, ToUpper(), String.Compare(string, string) etc. These methods can either return a value or not, or can have parameters or not. Methods are basically created for reuse, create once and we can use many times, anywhere in our program.

Basic syntax of a method in C# is:
returnType methodName(parameterList)
For example:

// The name of this method is AddNumbers which returns a value of type int and accepts two parameters, both of type int.
int AddNumbers(int num1, int num2)
{
     int sum = num1 + num2;
     return sum;
}
// The name of the method is SayHello. The return type of this method is void which means it does not return any value. 
// The parameter list is also empty, hence it does not accepts any parameter.
void SayHello()
{
    Console.WriteLine("Hellozz!");
}

Above are some of the ways you can create your own methods with/without parameters and with/without return values. The method names are normal variable names. We cannot have C# keywords as method names. Methods can have any number of parameters but can only return single value of any data type.

Calling/Invoking a Method
A method created is of no use until it is used anywhere in your program. A method can be used if it called somewhere in your program. Let’s use above created method in our program. Below is the sample code:

// In below class, there are three methods: Main() is the in-built method, AddNumbers() and SayHello() are custom methods.
class Program
{
        static void Main(string[] args)
        {
            // We are calling AddNumbers() method twice which indicate that we can reuse the methods.
            // We are passing two parameters of int type to AddNumbers() method which will return the sum of these two numbers.
            // We can use this returned value, in this case sum of two numbers, anywhere in our program.
            int sum = AddNumbers(20, 40);
            Console.WriteLine(sum);
            Console.WriteLine(AddNumbers(10, 34));
            SayHello();
        }
        static int AddNumbers(int num1, int num2)
        {
            int sum = num1 + num2;
            return sum;
        }
        static void SayHello()
        {
            Console.WriteLine("Hellozz!");
        } 
}

Below is the output of above code:

Verbatim Strings

When you prefix a string literal with the @ symbol, you have created what is termed a verbatim string.
Using verbatim strings, you disable the processing of a literal’s escape characters and print out a string
as is. This can be most useful when working with strings representing directory and network paths.
Therefore, rather than making use of \\ escape characters, you can simply use @

Below is the sample code:

Console.WriteLine(@"D:\MyFiles\MyPic.jpg");
string myLongString = @"This is a very
    very
    very
    long string";
Console.WriteLine(myLongString);
Console.WriteLine(@"David said ""Hello!! I am here!!""");

Below is the output of above code:

Escape Sequence in C#

C# contains various escape characters, which defines how the data should be printed on the output stream. Each escape character begins with a backslash, followed by a specific token.

Below is a table explaining the escape characters:

Escape Character Description
\’ Inserts a single quote into a string literal
\” Inserts a double quote into a string literal
\\ Inserts a backslash into a string literal. Used in defining file paths etc.
\a Triggers a System sound.
\n Inserts a new line
\r Inserts a carriage return
\t Inserts a horizontal tab into a string literal

Below is the sample code explaining the above escape characters:

Console.WriteLine("\"Hello World\"");
Console.WriteLine("\'Hello World\'");
Console.WriteLine("D:\\MyFiles\\MyPic.jpg");
Console.WriteLine("System Sound: \a");
Console.WriteLine("Hello\nNew Line");
Console.WriteLine("Orange\tYellow\tRed");

Below is the result of above code. You will also hear a system sound when this code is run.

Difference between Equals() and == in C# String

Equals() method and == sign are equality operators. The difference is that Equals() method is used to compare two strings that too only content where as == is used to compare two objects of any data type and compares the reference identity.

Lets see few examples:

String val1 = "Hello";
String val2 = "Hi";
Console.WriteLine("s1 = {0}", val1);
Console.WriteLine("s2 = {0}", val2);
Console.WriteLine();
Console.WriteLine("s1 == s2: {0}", val1 == val2);
Console.WriteLine("s1 == Hello: {0}", val1 == "Hello");
Console.WriteLine("s1 == HELLO: {0}", val1 == "HELLO");
Console.WriteLine("s1 == hello: {0}", val1 == "hello");
Console.WriteLine("s1.Equals(s2): {0}", val1.Equals(val2));
Console.WriteLine("Hi.Equals(s2): {0}", "Hi".Equals(val2));

Below is the result of the above code:

String name = "David";
char[] arrName = {'D','a','v','i','d'};
object myName = new String(arrName); 
Console.WriteLine("Result using == operator: {0}", myName == name);
Console.WriteLine("Result uisng Equals() method: {0}", myName.Equals(name));

Below is the result of above code:

null.Equals(value); returns the NulReferenceExceltion whereas value.Equals(null); returns the bool value. == operator can have null value on either side of the operator.
Below is a sample code: 

String name = "David";
String name1 = null;
Console.WriteLine("Result using == operator: {0}", name == name1);
Console.WriteLine("Result uisng Equals() method: {0}", name1.Equals(name));

Below is the result of the above code:

Strings in C#

String is nothing but a collection of characters be it collection of alphabets, alphanumeric or include special symbols. String is always enclosed within double quotes. Examples of String are: “Hello”,”Hello World!”,”P@ssw0rd2018″ etc.

We can do lots of manipulation on these string values. System.String provides a number of methods that we can use to manipulate these values. Lets see how to do that. I am creating a Console Application StringDemo.

Assign value to a string variable:

String value = "Hello World";

Concat()
We can concatenate two or more string values in one using plus (+) sign or using
Concat function.

String val1 = "My name is";
String val2 = "David";
String val3 = "Miller";
String val4 = val1 + " " + val2 + "!";
Console.WriteLine("Concatenated Value using + sign: " + val1 + " " + val2);
Console.WriteLine("Value of val4: " + val4);
String val5 = String.Concat(val1, " ",val2, " ", val3);
Console.WriteLine("Concatenated value using Concat function: " + val5);

Below is the result of the above code:

Length
Length is used to calculate the number of characters that are there in the string. It also counts the space characters. Result of below code is:

String value = "Hello World";
Console.WriteLine("Length of " + value + "is: " + value.Length);

Below is the result of the above code:

Compare()
C# is case-sensitive. Hence Hello is different from hello. Compare function is used to compare two strings. This function returns an integer value. If this returns 0, he values are same. If this returns 1, values are different. Below is the sample code:

String val1 = "Hello";
String val2 = "Hello";
String val3 = "hello";
int result = String.Compare(val1, val3);
int result1 = String.Compare(val1, val2);
int result2 = String.Compare(val1, val3, true);
Console.WriteLine("Comparison of Hello and hello: " + result);
Console.WriteLine("Comparison of Hello and Hello: " + result1);
Console.WriteLine("Comparison of Hello and hello, ignored the case: " + result2);

Below is the result of the above code:

Contains()
This method determines whether a string contains a specified substring. It will return a bool value, either true or false.
Below is a sample code:

String val = "Hello World";
bool result = val.Contains("Wor");
bool result1 = val.Contains("Hi");
Console.WriteLine("Hello World contains Wor? " + result);
Console.WriteLine("Hello World contains Hi? " + result1);

Below is the result of the above code:

Insert()
Insert() method inserts a specified string within a string at a given index. The index starts with 0.

String original = "HelloWorld!";
Console.WriteLine("The original string: '{0}'", original);
String updated = original.Insert(5, " ");
Console.WriteLine("The modified string: '{0}'", updated);
String updated1 = original.Insert(5, " Big ");
Console.WriteLine("The modified string: '{0}'", updated1);

Below is the result of above code:

PadLeft(), PadRight()
These methods are used to pad a character either left or right of a string.
Below is the sample code:

String name = "David";
char char1 = '*';
Console.WriteLine(name.PadLeft(15, char1));
Console.WriteLine(name.PadLeft(3, char1));
Console.WriteLine(name.PadRight(15, char1));
Console.WriteLine(name.PadRight(6, char1));

Below is the output of above code:

Insert(), Remove(), Replace()
Insert() method is used to insert a given string into another string at a specific index.
Remove() method is used to delete a specified number of characters from a specified string.
Replace() method is used to replace all occurrences of a specified character with another character in a specified string.
Below is the sample code for above method:

String str = "Hello World!";
Console.WriteLine("str = " + str);
Console.WriteLine("str.Insert(6, \"Hi \") : " + str.Insert(6, "Hi "));
Console.WriteLine("str.Remove(7,2) : " + str.Remove(7,2));
Console.WriteLine("str.Remove(7) : " + str.Remove(7));
Console.WriteLine("str.Replace(7,2) : " + str.Replace('l','*'));
Console.WriteLine("str.Replace(\"ll\",\"12\") : " + str.Replace("ll","12"));

Below is the result of above code:

Split()
This method is used to split a string in an array.
Below is the sample code for above method:

String str = "Orange,Yellow,Red,Green,Blue";
String[] colors=str.Split(',');
Console.WriteLine("str: " + str);
Console.WriteLine("Split character: \',\'");
Console.WriteLine();
Console.WriteLine("Result after splitting the string using \"str.Split(\',\')\"");
foreach(String s in colors)
{
    Console.WriteLine(s);
}

Below is the result of the above code:

Trim()
Trim() removes all the leading and trailing white-space characters from the string.
Below is the sample code:

String str = " Hello World ";
Console.WriteLine("str: " + str + "!");
Console.WriteLine("str.Trim(): " + str.Trim() + "!");

Below is the result of above code:

ToUpper(), ToLower()
ToUpper() is used to convert the complete string in upper-case.
ToLower() is used to convert the complete string in lower-case.
Below is the sample code:

String str = "Hello World!";
Console.WriteLine("str: " + str);
Console.WriteLine("str.ToUpper() : " + str.ToUpper());
Console.WriteLine("str.ToLower() : " + str.ToLower());

Below is the output of above code:

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started