Monday, 31 August 2020

Learn C# quickly in easy way

 

Learn C# quickly

 · August 31, 2018

 

C# is a object oriented programming language. It was developed by Microsoft.

You need to do some required software’s for compiling the programs. You can download visual studio 2017 community edition and install it in your computer.

C# is a commanding, powerful and flexible programming language like all programming languages. It can be used to create a variety of applications. C# is already used for projects as miscellaneous as dynamic Web sites, development tools, and even compilers. C# was created as an object-oriented programming (OOP) language

 

Note: In this article I am going to use only simple  keywords which you can understand so that you can learn C# quickly. Few keywords may seem technical but those are program keywords.

 

C# is a language derived from C and C++, but it was created from the ground up. Microsoft started with what worked in C and C++ and included new features that would make these languages easier to use. Many of these features are very similar to what can be found in Java. Ultimately, Microsoft had a number of objectives when building the language

 

Why we learn

·      C# is simple, readable and easy to use.

(C# removes some of the complexities and pitfalls of languages such as Java and C++, including the removal of macros, templates, multiple inheritance, and virtual base classes. These are all areas that cause either confusion or potential problems for C++ developers. If you are learning C# as your first language, rest assured -- these are topics you won't have to spend time learning!  Note: If you have used Java and you believe it is simple, you will find C# to be simple. Most people don't believe that Java is simple. C# is, however, easier than Java and C++.)

 

·      C# Is Modern

What makes a modern language? Features such as exception handling, garbage collection, extensible data types, and code security are features that are expected in a modern language. C# contains all of these.

(Note: Pointers are an integral part of C and C++. They are also the most confusing part of the languages. C# removes much of the complexity and trouble caused by pointers. In C#, automatic garbage collection and type safety are an integral part of the language)

 

·      C# Is Object-Oriented

The keys to an object-oriented language are encapsulation, inheritance, and polymorphism. C# supports all of these. Encapsulation is the placing of functionality into a single package. Inheritance is a structured way of extending existing code and functionality into new programs and packages. Polymorphism is the capability of adapting to what needs to be done. Understand, these are very simplistic definitions. The implementation of these is a bit more complicated.

·      C# Is Powerful and Flexible

As mentioned before, with C# you are limited only by your imagination. The language places no constraints on what can be done. C# can be used for projects as diverse as creating word processors, graphics, spreadsheets, and even compilers for other languages.

·      C# Is a Language of Few Words

C# is a language that uses a limited number of words. C# contains only a handful of terms, called keywords, which serve as the base on which the language's functionality is built. Table 1.1 lists the C# keywords. A majority of these keywords are used to describe information. You might think that a language with more keywords would be more powerful. This isn't true. As you program with C#, you will find that it can be used to do any task.

The C# Keywordsabstract   as         base     bool      breakbyte       case       catch    char      checkedclass      const      continue decimal   defaultdelegate   do         double   else      enumevent      explicit   extern   false     finallyfixed      float      for      foreachgoto       if         implicit in        intinterface  internal   is       lock      longnamespace  new        null     object   operatorout        override   params   private  protectedpublic     readonly   ref      return   sbytesealed     short      sizeof   stackallocstatic     string     struct   switch   thisthrow      true       try      typeof   uintulong      unchecked  unsafe   ushort   usingvirtual     void      while

 

·      C# Is Modular

C# code can (and should) be written in chunks called classes, which contain routines called member methods. These classes and methods can be reused in other applications or programs. By passing pieces of information to the classes and methods, you can create useful, reusable code.

·       

·      C# is a multi-paradigm programming language.

·      C# runs on a solid well-engineered .

·      C# is cross-platform. ...

·      C# is mature, popular and in very active development. ...

·      C# is Open-Source and led by Microsoft.

Lets see some advantages of C# languages.

1.    Automatic garbage collections.

2.    Standard library.

3.    Assembly versioning.

4.    Events and properties.

5.    Indexers.

6.    Linq and Lambda expressions.

7.    Windows integration.

8.    Easy generics.

9.    Multi-threading.

10.       Events and delegates management.

Lets go to the topic. Below are the topics which i am going to discuss with examples.

1.    Syntax.

2.    Comments.

3.    Data Types.

4.    Variables.

5.    Type Conversions.

6.    Constants.

7.    Operators.

8.    Loops.

9.    Switch.

10.       Arrays.

11.       Namespace.

12.       Methods.

13.       String Manipulation.

14.       Class.

15.       Struct.

16.       Enums.

17.       Inheritance.

18.       Polymorphism.

19.       Overloading operator.

20.       Interface

21.       Try.

22.       Catch.

23.       Multiple Catch.

24.       Final.

25.       File I/O.

C# – Syntax:

You can easily learn c# in one day, if you know the basic syntax of the C# language. Like the common object oriented languages, C# language has simple an common syntax which looks much like the C and C++ language.

public class HelloWorld                    //creating a class (public: access the class throughout the program)

   {                                       //starting a class

      static void Main(string[] args)      //function or method

      {                                    //creating a function

         Console.WriteLine("Hello World"); //displays a value in console

         Console.ReadLine();               //holds the command prompt from closing

      }                                    //ending a function

   }                                       //ending a class

Above code will open a command prompt and displays “Hello World”. Class was declared as public so you can access any of the methods created inside throughout the program.

C# – Comments:

1.     // -> one line comment.

2.    /* Your comments here*/ -> Multiple line comments.

public class HelloWorld                   //One line comment

   {                                      

/* Multiple line comment

line 1

line 2 */

      static void Main(string[] args)    

      {                                   

         Console.WriteLine("Hello World");

         Console.ReadLine();             

      }                                   

   }

Tip: /// -> This syntax can be used to trigger a comment summary in your Visual Studio 2017.

C# – Data Types:

Data types can be categorized into 3 types.

1.    Value types

2.    Pointer types

3.    Reference types

Please refer the data types in detail to learn C# data types.

Values Types:

Below are the value data types you can use in your C# program.

Type

Represents

Range

Default Value

bool

Boolean value

True or False

False

byte

8-bit unsigned integer

0 to 255

0

char

16-bit Unicode character

U +0000 to U +ffff

‘\0’

decimal

128-bit precise decimal values with 28-29 significant digits

(-7.9 x 1028 to 7.9 x 1028) / 100 to 28

0.0M

double

64-bit double-precision floating point type

(+/-)5.0 x 10-324 to (+/-)1.7 x 10308

0.0D

float

32-bit single-precision floating point type

-3.4 x 1038 to + 3.4 x 1038

0.0F

int

32-bit signed integer type

-2,147,483,648 to 2,147,483,647

0

long

64-bit signed integer type

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

0L

sbyte

8-bit signed integer type

-128 to 127

0

short

16-bit signed integer type

-32,768 to 32,767

0

uint

32-bit unsigned integer type

0 to 4,294,967,295

0

ulong

64-bit unsigned integer type

0 to 18,446,744,073,709,551,615

0

ushort

16-bit unsigned integer type

0 to 65,535

0

Pointer type:

You can use these type of variables to store the pointers. i.e. it was used to store the memory address of another data type.

E.g:

int* iptr;

 

char* cptr;

Reference type:

Reference type is used to store the references to their data objects. Below are some of the reference type examples.

The following keywords are used to declare reference types:

§  class

§  interface

§  delegate

C# also provides the following built-in reference types:

§  dynamic

§  object

§  string

C# – Variables:

Variables are nothing but a name that you assign to the storage location. Variables can be of different types such as integer, float, decimal, string etc…You need to assign a name which can be understandable by the coders.

variables

Syntax:

<data_type> <variable_name> = value;

Eg:

int i, j, k;

char c, ch;

float f, salary;

double d;

Above are declared variables, but if you want to initialize a variable, then you need to assign values to the variable, like you fill the storage area with necessary content which you need to store.

C# – Type Conversions:

Type conversions are used to convert one data type to another data type. Thought you cant able to convert all the available data type to necessary data, below are some of the data type conversion methods you can use.

type_conversion

Sr.No.

Methods & Description

1

ToBoolean

Converts a type to a Boolean value, where possible.

2

ToByte

Converts a type to a byte.

3

ToChar

Converts a type to a single Unicode character, where possible.

4

ToDateTime

Converts a type (integer or string type) to date-time structures.

5

ToDecimal

Converts a floating point or integer type to a decimal type.

6

ToDouble

Converts a type to a double type.

7

ToInt16

Converts a type to a 16-bit integer.

8

ToInt32

Converts a type to a 32-bit integer.

9

ToInt64

Converts a type to a 64-bit integer.

10

ToSbyte

Converts a type to a signed byte type.

11

ToSingle

Converts a type to a small floating point number.

12

ToString

Converts a type to a string.

13

ToType

Converts a type to a specified type.

14

ToUInt16

Converts a type to an unsigned int type.

15

ToUInt32

Converts a type to an unsigned long type.

16

ToUInt64

Converts a type to an unsigned big integer.

Eg:

int x = 10;

MessageBox.Show(x.ToString());

//Displays the integer as string in message box.

Type conversions completely depend on the type of data which you are going to convert. There are certain methods available which do throw error if the type conversions doesn’t work much like we want.

C# – Constant:

If you assign a constant variable , then this variable cannot be modified at the time of execution.

Constant can be of any type like integer, floating or character. Below are some of the literals which we can use

212           

215u         

0xFeeL       

3.14159      

314159E-5F

Character constants should always be enclosed inside single quotes and it can be assigned to a variable.

Escape sequence

Meaning

\\

\ character

\’

‘ character

\”

” character

\?

? character

\a

Alert or bell

\b

Backspace

\f

Form feed

\n

Newline

\r

Carriage return

\t

Horizontal tab

\v

Vertical tab

\xhh . . .

Hexadecimal number of one or more digits

Syntax:

const <data_type> <constant_name> = value;

Eg:

const int value = 10;

C# – Operator:

Operators are the symbols which was used by the compiler to do the arithmetic operations such as addition, multiplication, subtraction etc…There are 6 different kinds of operator.

§  Arithmetic Operators (+, -, *, ++, –, /, % etc…)

§  Relational Operators (=, !=, >=, <=, >, < etc…)

§  Logical Operators (&&, ||, !)

§  Bitwise Operators( &, |, ^ etc…)

§  Assignment Operators (=, += , -=, *=, !=, >>=, <<= etc…)

§  Misc Operators (sizeof(), typeof(), *,&,is,as etc…)

operators

Eg:

int a = 10;

int b = 10;

int c;

c = a + b;

C# – Loops:

In C# loops are used to execute the code several times. I.e you can run the code whenever the condition is satisfied or not, or you can run the code for specific number of times. Different kinds of loops which are using in C# are as follows

loops

While Loop:

while (<condition>)

            {

//do your stuff

            }

For Loop:

for (int i = 0; i < length; i++)

            {

 

            }

Do While Loop:

do while (<condition>)

                {

//do calculations

                }

Nested Loops:

for ( initialize; condition; increment ) {

   for ( initialize; condition; increment ) {

      statement(s);

   }

   statement(s);

}

Eg:

using System;

 

namespace Loops {

   class Program {

      static void Main(string[] args) {

         /* local variable definition */

         int i, j;

        

         for (i = 2; i < 100; i++) {

            for (j = 2; j <= (i / j); j++)

            if ((i % j) == 0) break; // if factor found, not prime

            if (j > (i / j)) Console.WriteLine("{0} is prime", i);

         }

         Console.ReadLine();

      }

   }

}

C# – Switch:

Switch can be used to execute a list of statements that matches the expression. There are various usage for switch statement and it was one of my favorite in C#.

Eg:

using System;

 

public class Example

{

   public static void Main()

   {

      int caseSwitch = 1;

     

      switch (caseSwitch)

      {

          case 1:

              Console.WriteLine("Case 1");

              break;

          case 2:

              Console.WriteLine("Case 2");

              break;

          default:

              Console.WriteLine("Default case");

              break;

      }

   }

}

C# – Array:

In C# Array is nothing but a sequential collection of data. In latest C# we are using list in most cases instead of array because of its simplicity and robust feature.

An array can be declared, initialized and cleared and than same can also be done in List. To learn C# in one day, then you need to know basic of arrays concept. Because while coding you will face challenges in handling arrays.

Syntax:

datatype[] arrayName;

Eg:

double[] balance = { 2340.0, 4523.69, 3421.0};

int [] marks = new int[5]  { 99,  98, 92, 97, 95};

int [] marks = new int[]  { 99,  98, 92, 97, 95};

An array can be accessed with the help of its sequence number which start from 0.

Eg:

double salary = balance[9];

C# – Namespace:

Namespace is used to keep the names separately to avoid avoid conflicts between different classes. Once a namespace is given to a class then specific class in C# can be called with the help of the namespace. It will not conflict with the other classes.

using System;

namespace first_space {

   class namespace_name {

      public void function() {

         Console.WriteLine("It wirks");

      }

   }

}

namespace

C# – Methods:

In C# Methods are called as a group of statements that produces output. This output can also be used by another method. This is the basic for learning C#, because if you want to learn any kind of language, then you need to know how to create and call methods. below is the syntax for the methods.

To learn C# in one day, then you need to know basic of how methods can be created.

<Access Specifier> <Return Type> <Method Name>(Parameter List) {

   Method Body

}

In many cases method was also called as functions. Here access specifiers are

1.    public.

2.    private.

3.    protected.

4.    internal

method

Return type can be of any data type which you are going to return such as string, list, integer etc. You need to give a name for the method and you can also pass the parameters if you need. In order to learn C# in one day, you need to know how to create methods.

public int FindMax(int num1, int num2) {    

      int result;

      if (num1 > num2)

         result = num1;

      else

         result = num2;

      return result;

   }

C# – Class:

Class consists of operations that need to be performed during execution. It will enclose declared variables, group of methods which can be used by another classes i.e like a library which contains all the available operations predefined. To learn C# in one day, then you need to know basic of how class can be created.

Below is the syntax for creating class.

<access specifier> class  class_name {

   // member variables

   <access specifier> <data type> variable1;

   <access specifier> <data type> variable2;

   ...

   <access specifier> <data type> variableN;

   // member methods

   <access specifier> <return type> method1(parameter_list) {

      // method body

   }

   <access specifier> <return type> method2(parameter_list) {

      // method body

   }

   ...

   <access specifier> <return type> methodN(parameter_list) {

      // method body

   }

}

Eg:

public class Person

{

    // Field

    public string name;

 

    // Constructor that takes no arguments.

    public Person()

    {

        name = "unknown";

    }

 

    // Constructor that takes one argument.

    public Person(string nm)

    {

        name = nm;

    }

 

    // Method

    public void SetName(string newName)

    {

        name = newName;

    }

}

class TestPerson

{

    static void Main()

    {

        // Call the constructor that has no parameters.

        Person person1 = new Person();

        Console.WriteLine(person1.name);

 

        person1.SetName("John Smith");

        Console.WriteLine(person1.name);

 

        // Call the constructor that has one parameter.

        Person person2 = new Person("Sarah Jones");

        Console.WriteLine(person2.name);

 

        // Keep the console window open in debug mode.

        Console.WriteLine("Press any key to exit.");

        Console.ReadKey();

    }

}

// Output:

// unknown

// John Smith

// Sarah Jones

C# – String Manipulation:

Strings are one of the important part of the program. Without it you cant output a result and most of the results cannot be determined. So in-order to use strings in different ways, there are manipulation techniques available in C# such as string concatenation, finding sub-string, searching string, joining string, splitting string etc…

Eg:

string s3 = "Visual C# Express";

System.Console.WriteLine(s3.Substring(7, 2));

// Output: "C#"

 

System.Console.WriteLine(s3.Replace("C#", "Basic"));

// Output: "Visual Basic Express"

 

// Index values are zero-based

int index = s3.IndexOf("C");

// index = 7

Below are some escape sequence which you can use in the string manipulations.

Escape sequence

Character name

Unicode encoding

\’

Single quote

0x0027

\”

Double quote

0x0022

\\

Backslash

0x005C

\0

Null

0x0000

\a

Alert

0x0007

\b

Backspace

0x0008

\f

Form feed

0x000C

\n

New line

0x000A

\r

Carriage return

0x000D

\t

Horizontal tab

0x0009

\U

Unicode escape sequence for surrogate pairs.

\Unnnnnnnn

\u

Unicode escape sequence

\u0041 = “A”

\v

Vertical tab

0x000B

\x

Unicode escape sequence similar to “\u” except with variable length.

\x0041 = “A”

C# – Structs:

Struct is use to hold related value of various data types. It was used to hold small group of related data. Keyword used for struct is “Struct”. Below example shows how to declare struct in C#.

public struct Book 

{ 

    public decimal price; 

    public string title; 

    public string author; 

}

C# – Enum:

Enum is used to declare the named constants which is called as the enumerator list.

enum Day {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

We can also use initializers in enum to override default values.

C# – Inheritance:

In C# Inheritance is an important concept. You can write C# code without inheritance but it will take more time to complete the code because without inheritance you need to create and declare the variables and methods again and again.

To learn C# in one day, then you need to know basic of inheritance concept.

Inheritance is used to create a base class that gives us specific functionality and in another class the base class functionality can be inherited ( like importing and using) or it can be overridden.

Below is a simple example which can be used to know more about inheritance.

using System;

 

public class A

{

   private int value = 10;

 

   public class B : A

   {

       public int GetValue()

       {

           return this.value;

       }    

   }

}

 

public class C : A

{

//    public int GetValue()

//    {

//        return this.value;

//    }

}

 

public class Example

{

    public static void Main(string[] args)

    {

        var b = new A.B();

        Console.WriteLine(b.GetValue());

    }

}

// The example displays the following output:

//       10

C# – Polymorphism & Overloading Operator:

Polymorphism means having many shapes. It has two types

1.    Static Polymorphism.

2.    Dynamic Polymorphism.

Static Polymorphism:

Links a function with an object during run-time. It was differentiated into two different types.

Function Overloading:

Multiple functions having same function name is called function overloading.

Operator Overloading:

Redefining or overloading the builtin operator again and again is called operator overloading.

Dynamic Polymorphism:

It was used to create abstract class. Abstract class contains abstract methods.

using System;

using System.Collections.Generic;

 

public class Shape

{

    // A few example members

    public int X { get; private set; }

    public int Y { get; private set; }

    public int Height { get; set; }

    public int Width { get; set; }

  

    // Virtual method

    public virtual void Draw()

    {

        Console.WriteLine("Performing base class drawing tasks");

    }

}

 

class Circle : Shape

{

    public override void Draw()

    {

        // Code to draw a circle...

        Console.WriteLine("Drawing a circle");

        base.Draw();

    }

}

class Rectangle : Shape

{

    public override void Draw()

    {

        // Code to draw a rectangle...

        Console.WriteLine("Drawing a rectangle");

        base.Draw();

    }

}

class Triangle : Shape

{

    public override void Draw()

    {

        // Code to draw a triangle...

        Console.WriteLine("Drawing a triangle");

        base.Draw();

    }

}

 

class Program

{

    static void Main(string[] args)

    {

        // Polymorphism at work #1: a Rectangle, Triangle and Circle

        // can all be used whereever a Shape is expected. No cast is

        // required because an implicit conversion exists from a derived

        // class to its base class.

        var shapes = new List<Shape>

        {

            new Rectangle(),

            new Triangle(),

            new Circle()

        };

 

        // Polymorphism at work #2: the virtual method Draw is

        // invoked on each of the derived classes, not the base class.

        foreach (var shape in shapes)

        {

            shape.Draw();

        }

 

        // Keep the console open in debug mode.

        Console.WriteLine("Press any key to exit.");

        Console.ReadKey();

    }

 

}

 

/* Output:

    Drawing a rectangle

    Performing base class drawing tasks

    Drawing a triangle

    Performing base class drawing tasks

    Drawing a circle

    Performing base class drawing tasks

 */

C# – Interface:

Interface contains definitions and declarations for the class and struct. Interface may also contain related functions related to the class and struct.

interface

You can simple implement the interface which contains the predefined function declarations.

interface IEquatable<T>

{

    bool Equals(T obj);

}

 

public class Car : IEquatable<Car>

{

    public string Make {get; set;}

    public string Model { get; set; }

    public string Year { get; set; }

 

    // Implementation of IEquatable<T> interface

    public bool Equals(Car car)

    {

        if (this.Make == car.Make &&

            this.Model == car.Model &&

            this.Year == car.Year)

        {

            return true;

        }

        else

            return false;

    }

}

C# – Try & Catch:

Try Catch statement is used to execute the statements which was given inside the try block and throw the exception to the catch block. It was most widely used to debug the program. Each and every developers will use the try-catch statement and find out the error occurred while executing the statements.

To learn C# in one day, then you need to know basic of try-catch statement for debugging.

try_catch

Syntax:

try

{

//statement

}

catch

{

//catch and display the errors or exceptions.

}

Eg:

static void Main()  

{ 

    int n; 

    try  

    { 

        // Do not initialize this variable here. 

        n = 123; 

    } 

    catch 

    { 

    } 

    // Error: Use of unassigned local variable 'n'. 

    Console.Write(n); 

}

C# – Multiple Catch:

Multiple catch contains multiple catch block in the try-catch statement to catch manual or specific exceptions. But if you use “Exceptions” then it will catch all the exceptions which was thrown from try block.

static void Main()  

{ 

    int n; 

    try  

    { 

        // Do not initialize this variable here. 

        n = 123; 

    } 

    catch(SystemInvalidException) 

    { 

    } 

    catch(SystemArgumentException)

    { 

    } 

    catch(Exception) 

    { 

    } 

    // Error: Use of unassigned local variable 'n'. 

    Console.Write(n); 

}

C# – Final:

In try-catch block, the last block which we can use is final block. Whether or not whenever try-catch block runs, final block was always executed. This helps you to catch the database exceptions and dispose it in the final block even after throwing errors.

try

   {

      //logic or database operations

   }

catch

   {

      // catch exceptions

   }

finally

  {

      //this block is always executed.

  }

C# – File I/O:

It was called File Input and Output operations. In Windows whenever you are reading the files or writing the files, it was always done like a stream. So the input steam is used for reading the file and output stream is used for writing the file.

To learn C# in one day, then you need to know basic of handling file i/o operations.

There are different file stream classes which can be used to read and write files in different formats.

Sr.No.

I/O Class & Description

1

BinaryReader

Reads primitive data from a binary stream.

2

BinaryWriter

Writes primitive data in binary format.

3

BufferedStream

A temporary storage for a stream of bytes.

4

Directory

Helps in manipulating a directory structure.

5

DirectoryInfo

Used for performing operations on directories.

6

DriveInfo

Provides information for the drives.

7

File

Helps in manipulating files.

8

FileInfo

Used for performing operations on files.

9

FileStream

Used to read from and write to any location in a file.

10

MemoryStream

Used for random access to streamed data stored in memory.

11

Path

Performs operations on path information.

12

StreamReader

Used for reading characters from a byte stream.

13

StreamWriter

Is used for writing characters to a stream.

14

StringReader

Is used for reading from a string buffer.

15

StringWriter

Is used for writing into a string buffer.

Eg:

public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

        }

 

        private async void Button_Click(object sender, RoutedEventArgs e)

        {

            UnicodeEncoding uniencoding = new UnicodeEncoding();

            string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";

 

            byte[] result = uniencoding.GetBytes(UserInput.Text);

 

            using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))

            {

                SourceStream.Seek(0, SeekOrigin.End);

                await SourceStream.WriteAsync(result, 0, result.Length);

            }

        }

    }

From the above contents, you can learn c# in one day if and only you know the concepts clearly. I have only specified basic details about the concepts which was used in C# language. If you want to learn more in details, then you need to approach professionals to get in-depth knowledge about C#. Here is is the link from Microsoft where can get documentation for C#

 

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...