Skip to main content

Basics : C# programming for c++ programmers

1. Data Conversion:
          
 Implicit:
Implicit conversion is done by the compiler:
  • When there is no loss of information if the conversion is done
  •  If there is no possibility of throwing exceptions during the conversion.
Example: Converting an int to a float will not loose any data and no exception will be thrown, hence an implicit conversion can be done. 

Explicit:
Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast operator or the convert class in c#.

Example:
  int i = (int)f;
  float f = 100.25F;

Difference Parse() and TryParse() 

1. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns        a bool indicating whether it succeeded or failed.
2. Use Parse() if you are sure the value will be valid, otherwise use TryParse() .


2. Array:
An array is a collection of similar data types.

Example:

 int[] EvenNumbers = new int[3];
        EvenNumbers[0] = 0;
        EvenNumbers[1] = 2;
        EvenNumbers[2] = 4;

        // Initialize and assign values in the same line
 int[] OddNumbers = { 1, 3, 5};

EvenNumbers.Length; // to compare


Two-Dimensional Arrays:

Syntax:
2-dimensional array of strings as:

string [,] names;

or, a 3-dimensional array of int variables as:

int [ , , ] m;


Example:

int [,] a = new int [3,4] {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};


Example:

using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         /* an array with 5 rows and 2 columns*/
         int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
         int i, j;
       
         /* output each array element's value */
         for (i = 0; i < 5; i++)
         {
            for (j = 0; j < 2; j++)
            {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}


C# - Jagged Arrays:

A Jagged array is an array of arrays. You can declare a jagged array named scores of type int as:

int [][] scores;

Example:

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};
Where, scores is an array of two arrays of integers -
scores[0] is an array of 3 integers
scores[1] is an array of 4 integers.


Example:

using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         /* a jagged array of 5 array of integers*/
         int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
         int i, j;
       
         /* output each array element's value */
         for (i = 0; i < 5; i++)
         {
            for (j = 0; j < 2; j++)
            {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
            }
         }
         Console.ReadKey();
      }
   }
}


OUTPUT:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

3. Method Parameters:
  • Value  
  • Reference  ex: ref int i;  (at both declaration and defination)
  • Out  ex: out int i; (at both declaration and defination)
  • Parameter Array : ex: params int[] (at defination)

4. Static :
  • Static variables are variables which are a shared between class object.
  • Static members are created before class non ststic members.
  • Can’t use this object.
  • Should be called through name of the class.
  • To initialize static member we can have static constructors, but we can’t have access modifier on static constructor. And it will be invoked only once irrespective of instances.

5. Inheritance :
  • C# supports only single inheritance
  • C# doesn’t support multiple inheritance, but multi-level inheritance is possible.
  • Base class ctor is invoked first before derive class object.
  • Use public public baseClass: base(“param”) ctor for referring to base class ctor explicitly. 
  • Public class class_name: Inherited_class_name {}  -> Inheritance format
  • base keyword used to refer to base class
  • base class object can point to child class but not voice versa

6. Method hiding:   
     Same as Function overloading Add new keyword in addition to c++

Example: overriding class:   
public class Emplyee
{
Public virtual void display() {
}
}
public class fulltimeEmp: Emplyee
{
Public new void display() {
}
}

Function in base class get executed and derived class function hides.


7. Polymorphism:
     Virtual keyword in base class function same as c++ 
      Example: public virtual void func1() {}

     Override keyword in overriding function
      Example: public ovrride void func1() {}


8. Encapsulation:

Public  =  Same as c++
Private  =  Same as c++
Protected   =  Same as c++
Internal  = allows a class to expose anywhere within the assembly.(within executable)
Protected internal = Within the same assembly and from within a derived class in any other assembly.



9. nullable TYPE:
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.

< data_type> ? = null;

Example:

int? num1 = null;
        int? num2 = 45;
        double? num3 = new double?();
        double? num4 = 3.14157;
        bool? boolval = new bool?();
       
        Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);

Note:

Null Coalescing Operator (??) :
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand.

num3 = num1 ?? 5.34; 


10. C# - Strings(using System)

Example:
string fname, lname;
         fname = "Rowan";
         lname = "Atkinson";
       
         string fullname = fname + lname;
         Console.WriteLine("Full Name: {0}", fullname);
       
         //by using string constructor
         char[] letters = { 'H', 'e', 'l', 'l','o' };
         string greetings = new string(letters);
         Console.WriteLine("Greetings: {0}", greetings);
       
         //methods returning string
         string[] sarray = { "Hello", "From", "Tutorials", "Point" };
         string message = String.Join(" ", sarray);
         Console.WriteLine("Message: {0}", message);



11. STRUCTURE:

The C# structures have the following features:

  • Structures can have methods, fields, indexers, properties, operator methods, and events.

  • Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
  • Unlike classes, structures cannot inherit other structures or classes.
  • Structures cannot be used as a base for other structures or classes.
  • A structure can implement one or more interfaces.
  • Structure members cannot be specified as abstract, virtual, or protected.
  • When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
  • If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.


Class versus Structure:
Classes and Structures have the following basic differences:

  • classes are reference types and structs are value types

  • structures do not support inheritance

  • structures cannot have default constructor


12. CLASS IN C#:

  • The default access specifier for a class type is internal. Default access for the members is private.

  • C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. 

  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.




13. C# - Operator Overloading:

public static Box operator+ (Box b, Box c)



14. Namespace:
A namespace is designed for providing a way to keep one set of names separate from another.



Comments

Popular posts from this blog

const used with functions

const used with functions : class Dog {    int age;    string name; public:    Dog() { age = 3; name = "dummy"; }         // const parameters and these are overloaded functions    void setAge(const int& a) { age = a; }    void setAge(int& a) { age = a; }         // Const return value    const string& getName() {return name;}         // const function and these are overloaded functions    void printDogName() const { cout << name << "const" << endl; }  // value of name can't be modified    void printDogName() { cout << getName() << " non-const" << endl; } }; int main() {    Dog d;    d.printDogName();        const Dog d2;    d2.printDogName();     }

Structured Bindings

Returning multiple Values from function C++ 11 vs C++ 17 Returning compound objects Iterating over a compound collection Direct initialization Returning multiple Values from function C++ 11 vs C++ 17 :  C++ 11 (std::tie): std::tuple mytuple() {     char a = 'a';     int i = 123;     bool b = true;     return std::make_tuple(a, i, b);  // packing variable into tuple } To access return value using C++ 11, we would need something like: char a; int i; bool b; std::tie(a, i, b) = mytuple();  // unpacking tuple into variables Where the variables have to be defined before use and the types known in advance. C++ 17 : auto [a, i, b] = mytuple(); Returning compound objects :  This is the easy way to assign the individual parts of a compound type (such as a struct, pair etc) to different variables all in one go – and have the correct types automatically assigned. So let’s have a look at an ...

POST 1 : std::thread in c++ | C++ 11

std::thread   C++  Thread support library std::thread. Threads enable programs to execute across several processor cores. Defined in header Class : thread Member types : native_handle_type Data Member  id    //represents the id of a thread (public member class) Member functions (constructor)    //constructs new thread object (public member function) (destructor)    //destructs the thread object, underlying thread must be joined or detached  (public member function) operator=    //moves the thread object  Observers  // Covered in NEXT POST Operations    // Covered in NEXT POST Constructor :   #include   void f1 ( int n ) { for ( int i = 0 ; i < 5 ; ++ i ) { std:: cout << "Thread 1 executing \n " ; ++ n ; std:: this_thread :: sleep_for ( std:: chrono :: milliseconds ( 10 ) ) ; ...