Skip to content

Instantly share code, notes, and snippets.

@snghnishant
Last active September 16, 2020 07:59
Show Gist options
  • Save snghnishant/b3fed6971e58b1835f1bed1ce0a67508 to your computer and use it in GitHub Desktop.
Save snghnishant/b3fed6971e58b1835f1bed1ce0a67508 to your computer and use it in GitHub Desktop.
C# 101

Introduction to C#

Anatomy or structure of a C# program

/* A namespace is used to organise our classes and their methods in a herarchical manner.
This helps in avoiding method conflicts, suppose when two or more classes have same method
with different definition then we can mention explicitly their namespace.class.method for 
the method to use. */

using System; 
// The using is a directive that is used here to import the System namespace
namespace HelloWorld 
// creating our own namespace, here lives our Hello class and its methods
{
    class Hello 
    // class is keyword used to define the class name 
    {
        static void Main()
        // Main method is entry point for our program, void is the return type and static is keyword modifier 
        {
            Console.WriteLine("Hello World!");
            // Console is the class of System namespace imported at top, WriteLine() is the method of the class
        }
    }
}

Operators

  • Logical: && (AND), || (OR), !(NOT)
  • Mathematical: Add (+), Subtract(-), * Multiply, divide (/), % (Modulo)
  • Relational: <, >, >=, <=, ==, =
  • Bitwise: Binary AND (&), Binary OR (|), Binary XOR (^), 1's complement (~), Left Shift (<<), Right Shift(>>)

Datatypes

There are 3 types of data types supported in C#, which are Value, Pointer and Reference. Both value and reference data types can be system or user defined. Below are some system defined value data types in C#.

  • var
  • char
  • string
  • bool
  • short
  • int
  • long
  • float
  • double
  • decimal (much greater precision than double but with a smaller range)
// Program to demonstrate basic data types supported in C#
using System;
class DataTypes{
  static void Main(string[] args){
      // Integer Types
      short s = 10;
      int i = 100;
      long l = 1000;
      Console.WriteLine($"Short : {s}, Int: {i}, Long: {l}");

      // Float Types
      float f = 123.321f; // 7 digit precision
      double db = 120.78; // 15 digit precision
      decimal d = 21.347483924m; // 28 digit precision
      Console.WriteLine($"Float: {f}, Double: {db}, Decimal: {d}");

      // Other types
      bool b = true;
      char c = 'A';
      string str = "Nishant";
      Console.WriteLine($"Bool: {b}, Char: {c}, String: {str}");
   } 
}

Printing to console

Console.WriteLine("Hello World");

Declaring the variable

string name = "Nishant";
Console.WriteLine("Hello "+ name);

Integer Properties and Methods

int max = int.MaxValue; // gets maximum range value for integer as per size supported in the machine
int min = int.MinValue; // gets minimum range value for integer as per size supported in the machine

String concatenation

Console.WriteLine($"Hello {name}");

String Properties and Methods

Console.WriteLine(name.length);
string greeting = "   Hello World   " //this will include white spaces in string
Console.WriteLine(greeting.TrimStart()); //this will trim the left whitespace
Console.WriteLine(greeting.TrimEnd()); //this will trim right whitespace
Console.WriteLine(greeting.Trim()); // this will trim all whitespace
string sayHello = "Hello World";
sayHello = sayHello.Replace("Hello", "My"); // this will print My World
Console.WriteLine(sayHello.ToUpper()); //prints in uppercase
Console.WriteLine(sayHello.ToLower()); //prints in lowercase
Console.log(sayHello.Contains("My"); //prints True
Console.WriteLine(sayHello.Contains("Hello"); //prints False
Console.WriteLine(sayHello.StartsWith("World"); //prints False

Conditional

if(condition)
  statement 1;
 else
  statement 2;

Loops

// While loop
while(condition){
  statements;
  counter update statement;
}

// Do-While loop
do{
  statements;
  counter update statement;
}while(condition);

// For loop
for(initialize ; condition ; updation){
  statements;
}

// ForEach loop
foreach(d_type identifier in List){
  statements;
}

Lists

using System;
using System.Collections.Generic; // for using List<T>
namespace myconsoleapp{
class myClass{
static void Main(string[] args){
  var names = new List<string> {"Hello", "dear", "Nishant"};
  names.Add("and"); // pushes item to the list
  names.Add("Himanshu");
  names.Remove("dear"); // search and pops out the item form the list
  Console.WriteLine(names[2]); // prints the value at index 2 of list
  Console.WriteLine(names.Count); //prints the total number of elements in the List
  foreach(string name in names){
    Console.WriteLine(name); // prints all the names
    }
    Console.WriteLine(names.IndexOf("Nishant"));
    // searches and prints index of the search term in the list , if not found returns -1
    names.Sort(); // sorts the list items alphabetically
    }
  }
}

Arrays

  1. Static arrays are declared at compile time and the memory is allocated on stack. dataType array_name[array_size];
  2. Dynamic arrays are declared at runtime and the memory is allocated on heap, this can be donw using new keyword. dataType[] arrayName = new dataType[arraySize];
using System;
public class MainClass{
  public static void Main(String [] args){
    // Declaring and list initializing static arrays doesn't need size explicitly
    int[] staticArr = {1,2,3,4,5};
    foreach(int item in staticArr){
      Console.WriteLine($"{item}");
    }
    
    // Declaring and list initializing dynamic arrays
    int[] dynamicArr = new int[] {6,7,8,9,10};
    foreach(int item in dynamicArr){
      Console.WriteLine($"{item}");
    }

    // Implicitly typed arrays using var
    var arr1 = new [] { "one", "two", "three" };
        foreach(var item in arr1)
        {
            Console.WriteLine(item.ToString());
        }

  }
}

Multidimensional Arrays

You can create multidimensional array using the syntax dataType[,] arrayName = new dataType[row,column];

using System;

public class MainClass {

   public static void Main(String [] args)
   {
        int[,] arr = new int[4, 2] { {1, 1}, {2, 2}, {3, 3}, {4, 4} };
        // Access a member of the multi-dimensional array:
        Console.Out.WriteLine(arr[3, 1]); // 4
   }
}

Jagged Arrays

You can create jagged arrays which are multideimensional arrays without fixed column size using the syntax dataType [][] arrayName= new [rows][]; The second [] is initialized without a size and is done separately to initlize the sub arrays. It's recommended to use jagged arrays instead of Multidimensional arrays because they are faster and safer to use due to bad clr implementation of Multidimensional arrays in C#.

using System;

public class MainClass {

   public static void Main(String [] args)
   {
        int[][] a = new int[8][];
        for (int i = 0; i < a.Length; i++)
        {
           a[i] = new int[5]; // This will initialize column size to 5 for all the arrays
        }
        for (int i = 0; i < a[2].Length; i++)
        {
           Console.WriteLine(a[2][i]);
        }
   }
}

Functions

A function in C# is known as a method which is a sub routine that can be used to break complex task into smaller task and then can be used in a program, it follows the below syntax:

AccessModifier OptionalModifier ReturnType MethodName(InputParameters)
{
 //Method body
}
  • AccessModifier can be public, protected, private or by default internal.
  • OptionalModifier can be static, abstract, virtual, override, new or sealed.
  • ReturnType can be void for no return or can be any type from the basic ones, as int to complex classes.
  • A method may have some or no input parameters.
  • To set parameters for a method you should:
    1. declare each one like normal variable declarations (like int a)
    2. for more than one parameter you should use a comma between them (like int a, int b)

Parameters may have default values. You can set a value for the parameter (like int a = 0). If a parameter has a default value, setting the input value is optional.

using System;

class MethodExample
{
    public static int Sum(int a, int b) //method initialization
    {
        return a + b; //returning sum of a and b
    }

    static void Main()
    {
      int answer;
      answer = Sum(5,6); //calling method by passing appropriate arguments
      Console.WriteLine("answer is: {0}", answer); // prints 11
    }
}

Access rights

// static: is callable on a class even when no instance of the class has been created
public static void MyMethod()
  
// virtual: can be called or overridden in an inherited class
public virtual void MyMethod()
  
// internal: access is limited within the current assembly
internal void MyMethod()
  
//private: access is limited only within the same class
private void MyMethod()
  
//public: access right from every class / assembly
public void MyMethod()
  
//protected: access is limited to the containing class or types derived from it
protected void MyMethod()
  
//protected internal: access is limited to the current assembly or types derived from the containing class.
protected internal void MyMethod()

More on Functions

using System;

public class MainClass
{   
    static void SaySomething(string say = "Hello", string what= "World") {
        Console.WriteLine(say +'\t'+ what);
    }

    // Parameters with default value should come after parameters without default value
    static void sayHello(string name, string salutation="HYD"){
      Console.WriteLine($"Hey {name} {salutation}?");
    }

    // Call by Reference
    static void DoubleNumber(ref int x){
      x *= 2;
    }

    static void Main(String [] args)
    { // calling with default arguments
        SaySomething();

      // calling with arguments
        sayHello("Nishant", "KKRH");
      
      // calling with default arguments
        sayHello("Nishant");
      
      
      int num = 10;
      Console.WriteLine(num);
      DoubleNumber(ref num);
      Console.WriteLine(num);
    }
}

Method Overloading

using System;
class MethodOverloadingExample
{
    static void Main()
    {
        Console.WriteLine(Area(5)); //calling area function for square with int type parameter
        Console.WriteLine("Area of circle is: {0}", Area(5.5)); //calling area function for circle with double type parameter
        Console.WriteLine(Area(5.5, 6.5)); //calling area function for rectangle with double type parameters
    }
    public static string Area(int value1) //computing area of square
    {
        return String.Format("Area of Square is {0}", value1 * value1); 
    }
    public static double Area(double value1) //computing area of circle
    {
        return 3.14 * Math.Pow(value1,2); //using Pow to calculate the power of 2 of value1
    }
    public static string Area(double value1, double value2) //computing area of rectangle 
    {
        return String.Format("Area of Rectangle is {0}", value1 * value2);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment