Thursday, July 24, 2014

C# Tutorial

C# Programming for Beginners to Experts|  C#.NET Concepts |C# Interview Preperation
C# is a modern, general-purpose object-oriented programming language developed by Microsoft.
C# pronounced as “C Sharp” has several release as of today. Different versions of C# are:

1.      C#1.0/12 (.NET Framework 1.0/1/1), release date: Jan, 2002.

2.      C#2.0 (.NET Framework 2.0), release date: Sept, 2005.

3.      C# 3.0 (.NET Framework 2.0/3.0/3.5), release date: Aug, 2007.

4.      C#4.0 (.NET Framework 4), release date: Apr, 2010.

5.      C#5.0 (.NET Framework 4.5), release date: Jun, 2013.

C# Basics:

A C# program basically consists of the following parts:
·        Namespace declaration
·        A Class
·        Class method(s)
·        Attributes
·        A Main method
·        Statements & Expressions
·        Comments
Here is the sample code that prints “Hello World”:
using System;
 
namespace HelloWorldProgram
{
    class HelloWorld
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.Read();
        }
    }
}

Output:   Hello World

String

The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

Ex: 1.       string a = "hello";          string b = "h";
          // Append to contents of 'b'
          b += "ello";
 
          Console.WriteLine(a == b);
          Console.WriteLine((object)a == (object)b);

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance. 

*** Strings are immutable--the contents of a string object cannot be changed after the object is created. 

Ex: 2.
         string str = "test";
         char x = str[2];  // x = 's'; 

Ex: 3.

String literals can contain any character literal. Escape sequences are included.

The following example uses escape sequence \\ for backslash, and \n for newline.

string filename = @"c:\Docs\Source\a.txt";
string message = @""Hello! "\n How are you!";
String vs String Builder
Once created, a string cannot be changed. A StringBuilder can be changed as many times as necessary. It yields big performance improvements. It eliminates many string copies. And in certain loops, it is essential.
Append() method in string builder is used to append text.

AppendLine() method in string builder is used to append text with line terminator at the end.
 
Ex:

// Declare a new StringBuilder.

StringBuilder builderStates = new StringBuilder();

builderStates.AppendLine(“Andhra Pradesh”);

builderStates.AppendLine(“Arunachal Pradesh”);

---

--

-- 

Value Type vs Reference Type
“System.Object” is the base class from all the .NET classes.
Value types: Value types inherit from the System.ValueType class, which in turn, inherits from System.Object. Value types are stored on stack. They are implicitly sealed. Structs and Enumerations are value types and they are always stored on stack. A value type cannot contain a null value. Variables that are value types store data.

Reference types: Variables to reference types referred to as object, store reference to actual data. Actual data is stored on the heap and reference is stored on the stack. This allows the garbage collector to track outstanding references to a particular instance and free the instance when no references remain.


Integral types : sbytebytecharshortushortintuintlongulong

Floating Point types: float, double

Decimal types: decimal 

Boxing vs Unboxing
Converting a value type to reference type is called Boxing. Unboxing is converting a reference type to value type. Unboxing is the opposite operation and is an explicit operation.

Ex: int i = 123;
object o = (object)i;  // boxing


When boxing is done values stores on Heap memory.

 
Ex: object o = 123;
int i = (int)o;  // unboxing


When unboxing is done values stores on Stack memory. 

C# File I/O
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.

The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and the output stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
File Class
File class is used for the File operations in C#. We can create, delete, copy etc. operations do with C# File class.
1. To create a file: File.Create("c:\\testFile.txt");
2. To check if file exists: File.Exists("c:\\testFile.txt")
3. To create a file: File.Create("c:\\testFile.txt");
 
Path Class
C# provides effective ways of dealing with filenames and paths from its namespace System.IO . The Path Class performs operations on String instances that contain file or directory path information. The members of the Path class enable you to quickly and easily perform common operations such as returns filename, extensions etc.
The following are the some important operations in C# Path Class:
GetDirectoryName - Returns the directory information for the specified path string. GetExtension - Returns the extension of the specified path string.
GetFileName - Returns the file name and extension of the specified path string.
GetFileNameWithoutExtension - Returns the file name of the specified path string without the extension.
GetFullPath - Returns the absolute path for the specified path string.
Directory Class
The System.IO.Directory class offers methods form creating, deleting, moving, retrieving file lists, and many more. These methods are static so you don't need to create an instance of that class. The following table shows you some usefull methods of the Directory class that you can use.

Methods
Description
CreateDirectory
Creates a new directory.
Delete
Deletes an existing directory.
Exists
Tells whether a given directory exists in the file system.
GetCurrentDirectory
Gets the current working directory of the application.
GetDirectories
Gets the name of the subdirectories of the specified directory.
GetFiles
Returns the names of the files contained in the specified directory.
GetSystemFileEntries
Returns an array of strings which are the names of the files and subdirectories in the specified directory.
GetParent
Get the root directory of a specified path.
Move
Moves the directory including its contents into another location.

Creating a New Directory


We use the CreateDirectory method to create a new directory. The following code snippet shows how to do that.

Directory.CreateDirectory(@"C:\Directory\Subdirectory");

The CreateDirectory method accepts one string argument which is the path. The CreateDirectory method will create all the directories and subdirectories specified by the path.

Deleting a Directory


Use the Delete method if you want to delete a directory. The Delete method accepts a string argument which is the path of the directory.

Directory.Delete(@"C:\Directory\Subdirectory");

By default, the Delete method will produce an exception if the directory to be deleted is not empty. If you want to include all the files and subdirectory of the directory that you will be deleting, then you can use an overloaded version of the Delete method that has a second boolean parameter. When this is set to true, then everything that the specified directory contains will be deleted as well.

Directory.Delete(@"C:\Directory\Subdirectory", true);

Testing if the Directory Exists

Like the System.IO.File class, the Directory class also has an Exists method which tells whether a specified path of the directory exists inside the file system.
if (Directory.Exists(@"C:\Directory\Subdirectory"))
   Console.WriteLine("The directory exists.");

Getting the List of Subdirectories and Files

The GetDirectories method gets all the subdirectories of the specified path. For demonstration, let's create a directory C:\Directory and inside it, create directories named Subdirectory1, Subdirectory2, and Subdirectory3. The following code will list the directories inside C:\Directory.


string[] directories = Directory.GetDirectories(@"C:\");
 
foreach (string directory in directories)
{
    Console.WriteLine(directory);
}
If you only want to display the subdirectory name, then we do some string manipulation.

Console.WriteLine(directory.Substring(directory.LastIndexOf(@"\") + 1));

Alternatively, you can use the methods by System.IO.Path which will be discussed in a later lesson.

The GetFiles and GetSystemFileEntries is similar to the GetDirectory class. The GetFiles method returns a string array containing the list of files inside the directory. The GetSystemFileEntries is the combined list of files and directories.

Moving a Directory

To move a directory to another location, simply use the Move method which accepts two arguments, the directory to move and the path the directory will be moved to.
Directory.Move(@"C:\Directory", @"C:\AnotherDirectory\Directory");

 Exception Handling
Exceptions are the errors/problems that happen in a program.
Exceptions in C# are handled using try/catch blocks.
For example: divide by zero, validating user input, checking for null objects and handling database connections.
C# exception handling is built upon four keywords: try, catch, finally and throw.
    try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

    catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

    finally: The finally block is used to clean up activities. It execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

    throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Syntax:
try
{
   // statements causing exception

}

catch( ExceptionName e1 )

{

   // error handling code

}

catch( ExceptionName e2 )

{

   // error handling code

}

catch( ExceptionName eN )

{

   // error handling code

}

finally

{

   // statements to be executed
}

Example:

using System;
using System.IO;

class tryCatchDemo
{
    static void Main(string[] args)
    {
        try
        {
            File.OpenRead("NonExistentFilePath");
        }
        catch(FileNotFoundException fnfex)
        {
            Console.WriteLine(fnfex.ToString());
        }
        catch
(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

Throw:
     You can explicitly throw an exception using the throw statement. You can also throw a caught exception again using the throw statement. It is good coding practice to add information to an exception that is re-thrown to provide more information when debugging.

   throw new ApplicationException("Some message");
 

System.Exception class handles errors. It is a base class for all exception classes.

Exception Class
Description
System.IO.IOException
Handles I/O errors.
FileNotFoundException
Handles when I file not exists
DirectoryNotFoundException
Handles when directory not found
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.
System.NullReferenceException
Handles errors generated from deferencing a null object.
System.DivideByZeroException
Handles errors generated from dividing a dividend with zero.
System.InvalidCastException
Handles errors generated during typecasting.
System.OutOfMemoryException
Handles errors generated from insufficient free memory.
System.StackOverflowException
Handles errors generated from stack overflow.



 
Delegates and Events
 
Delegates are reference to functions or Delegates hold a reference to a method. A delegate is a class that allows you to reference a method.
Delegates allow methods to be passed as parameters.
Syntax:
Delegate <type> SomeDelegateName(parameters);
Ex:
using System;

namespace BasicDelegateTest
{
    // Declaration
    public delegate void SimpleDelegate();

    class TestDelegate
    {
        public static void MyFunc()
        {
            Console.WriteLine("I was called by delegate ...");
        }

        public static void Main()
        {
            // Instantiation
            SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

            // Invocation           
simpleDelegate();} }}

Events:

Events are basically actions. Events occur when user clicks button, dropdown selected or mouse movements, etc…
A Button is a class, when you click on it, the Click event fires.
A Timer is a class, every millisecond a tick event fires.
Ex:
   EventHandler delegate to a Button Click event.

  this.button1.Click += new System.EventHandler(this.button1_Click);

 
Using Attributes
Attributes are elements that allow you to add declarative information to your programs. For example, there are attributes such as DllImportAttribute that allow a program to communicate with the Win32 libraries. Another attribute, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know that a method should no longer be used.
Ex:
class
BasicAttributeDemo
{
    [Obsolete]
    public void MyFirstdeprecatedMethod()
    {
        Console.WriteLine("Called MyFirstdeprecatedMethod().");
    }
    // make the program thread safe for COM
    [STAThread]
    static void Main(string[] args)
    {
        BasicAttributeDemo attrDemo = new BasicAttributeDemo();

        attrDemo.MyFirstdeprecatedMethod();    }
}

Access Modifiers
Private
Protected
Internal
Protected Internal
Public
Private: Access is limited to within the class definition. This is the default access modifier type if none is formally specified.
Protected:  Access is limited to within the class definition and any class that inherits from the class.
Internal:
Access is limited exclusively to classes defined within the current project assembly.
Protected Internal: Protected internal member is accessible anywhere in the project as well as It is also available to classes that inherit from the current assembly only.
Public: No restrictions to access. The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Static
·         Static is a modifier which belongs to the type itself rather than to a specific object.
·         The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors.
·         Static member memory location cannot be changed.
·         Static member belongs to class but not to any instance.
·         Static members are called directly with class names but not with object of class.
·         Static members are declared with "static" keyword.
Ex:
class StaticTestClass
    {
        int x;
        static int y; 

        void myMethod()
        {
          // some code
        }
        static void myStaticMethod()
        {
           // some code
        } 

        static void Main()
        {
            StaticTestClass testObj = new StaticTestClass();

           
// Instance members
            testObj.x = 1;
            testObj.myMethod(); 

            //Static members
            StaticTestClass.y = 100;
            StaticTestClass.myStaticMethod();          
        }    }

Math Class also contains several static methods (like Max, Min, Round, Sqlrt, etc..).
Ex:    System.Math.Max
         System.Math.Min
         System.Math.Round
 

Static Class
Static class is similar to a class, but static class cannot be instantiated. i.e you cannot use new keyword for static classes.

Because there is no instance variable, you access the members of a static class by using the class name itself.
Ex:
The following class is declared as static and contains only static methods:

    static class CompanyEmployee
    {        public static void DoSomething() { /*...*/ }
        public static void DoSomethingElse() { /*...*/  }
    }
A static member cannot be referenced through an instance. Instead, it is referenced through the type name.
i.e method names are called directly with classname.
Ex:        CompanyEmployee. DoSomething();
      CompanyEmployee. DoSomethingElse();
 

Generic Collections
Collections
      
In .NET V1.0, we have collections using ArrayList. ArrayList stores any type as an object. Unlike Array, ArrayList stores different types. Which will cause errors at runtime. Generic collections will fix these issues.

             Generics are the most powerful feature of C# 2.0. Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code.

To do that, use the < and > brackets, enclosing a generic type parameter.

Creating Generic List<T> Collections:

Ex:
The following list creates all integer values.

   List<int> listIntValues = new List<int>(); 

            listIntValues.Add(30);

            listIntValues.Add(90);

            listIntValues.Add(270); 

            foreach (int intVal in listIntValues)
            {
                Console.WriteLine("My Int Value: {0}", intVal);
            }
Similarly we can create list of different types.
 

A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it.
Dictionary<TKey, TValue> Collections:
           Another very useful generic collection class is the Dictionary, which works with key/value pairs. There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object.

Ex:
Dictionary<int, string> customers = new Dictionary<int, string>(); 

            customers.Add(1000, "Express Electronics");
            customers.Add(1001, "Bharat Electronics");
            customers.Add(1002, "Videocon"); 

            foreach (KeyValuePair<int,string> pair in customers)
            {
                Console.WriteLine("Customer ID: {0} | Customer Name:{1}", pair.Key, pair.Value);              

            }

Note: Generic collection classes are in System.Collections.Generic” namespace.

Object-Oriented Programming (C# and Visual Basic)

Object-oriented programming (OOP) is a programming paradigm(model or pattern) that uses objects and their interactions to design applications and computer programs.
Object:
Object is the basic unit of object-oriented programming. Objects are identified by its unique name. An object is an instance of a class.
Class:
A class is a group of things. Class groups together variables of different types, properties, methods and events.
A Class is used to create instances or objects at run time.
A class is a reference type.
Basic OOPs Concepts are:
·         Abstraction
·         Encapsulation
·         Inheritance
·         Polymorphism
Abstraction is the ability to hide methods and properties of object. It is used to display only necessary and essential features of an object to the outside world.
This is achieved by using access modifiers like private, protected, public, etc...
Encapsulation
Encapsulation
means a group of related properties, methods, and other members are treated as a single unit or object.
Encapsulation binds together code and the data it manipulates and keeps them both safe from outside interference and misuse.
Inheritance:
Inheritance is the process of acquiring the properties of base class in to derived class.
Inheritance is getting parent class properties into child class.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.

class DerivedClass : BaseClass{}


Note: C# doesn’t support multiple Inheritance.
(Class A -> Class B is OK, but A->B->C is not OK).

By default all classes can be inherited. However, you can specify whether a class must not be used as a base class, or create a class that can be used as a base class only.

To specify that a class cannot be used as a base class:

1.  public sealed class A { }  à Sealed Class
2.  public Abstract class X {} à Abstract Class



Polymorphism: 

‘Poly’ means many. Polymorphism means having many forms or multiple behavior.

In OOP the polymorphisms is achieved by using many different techniques: method overloading, operator overloading, and method overriding.
It allows you to invoke derived class methods through a base class reference during run-time.

Ex:
Base Class with Virtual Method

using
System;

public class DrawingObject
{
    public virtual void Draw()
    {
        Console.WriteLine("I'm just a generic drawing object.");
    }
}
Note: The virtual modifier indicates to derived classes that they can override this method.

 Ex: Derived Classes with Override methods

using
System;

public class Line : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Line.");
    }
}

public
class Circle : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Circle.");
    }
}

public
class Square : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Square.");
    }
}

These classes inherit the DrawingObject class. Each class has a Draw() method and each Draw() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.

Ex: Program Implementing Polymorphism

using System;

public class DrawDemo
{
    public static int Main( )
    {
        DrawingObject[] dObj = new DrawingObject[4];

        dObj[0] = new Line();
        dObj[1] = new Circle();
        dObj[2] = new Square();
        dObj[3] = new DrawingObject();

        foreach
(DrawingObject drawObj in dObj)
        {
            drawObj.Draw();
        }

        return 0;
    }
}

Output:


I'm a Line.

I'm a Circle.

I'm a Square.

I'm just a generic drawing object.

 
Abstract and Sealed Classes

Abstract classes cannot be instantiated. Abstract classes are declared with keyword abstract. It can only be used as a super-class for other classes that extend the abstract class.
Abstract class is the concept and implementation gets completed when it is being realized by a subclass.

In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.
Abstract class can have abstract as well as non-abstract methods.

Ex:

public abstract class MyAbstractClass
{
       // …
 
       protected void SampleMethod1()
       {
              // …
             Console.WriteLine(“Hello”);
       }

       protected void SampleMethod2()
       {
              // …
             Console.WriteLine(“How are you?”);
       } 

       public abstract void MyAbstractMethod();
} 

Notice how in the example above the ordinary methods SampleMethod1() and SampleMethod2() have a body, while the abstract method MyAbstractMethod() does not. Notice that the methods are declared as protected.

Here is how the implementation of the above abstraction looks like:

public class MyCommonClass : MyAbstractClass
{
       public override bool MyAbstractMethod ()
       {
              /// --
              /// --do something.
///--

             
return true;
       }
}

Similary, Sealed classes also used a super-classes only, no other classes can inherit sealed class. Sealed classes are declared with a keyword: sealed

Interface
An Interface is similar to class or struct declaration.
An interface contains only the signatures of methods, properties, events.
A class or struct that implements/inherits the interface must implement the members of the interface that are specified in the interface definition. 

Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. 

   interface ISampleInterface
    {
 int i { get; set; }
        void SampleMethod();
    }

    class ImplementationClass : ISampleInterface
    {
        // Explicit interface member implementation: 
int ISampleInterface.i
        {
            get { return 10; }
            set { value = 200; }
        }
        void ISampleInterface.SampleMethod()
        {
            // Method implementation.
        }      
        static void Main()
        {
            // Declare an interface instance.
            ISampleInterface obj = new ImplementationClass(); 

            // Call the member.
            obj.SampleMethod();
        }
    }

·         Interfaces in C # provide a way to achieve runtime polymorphism. Using interfaces we can invoke functions from different classes through the same Interface reference.
·          An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body.
·         You cannot instantiate an interface.
·         An interface is similar to an abstract class with one point i.e both cannot be instantiated 

Interfaces vs Abstract classes

Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constrants defined.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour then abstract class is better to use.
Polymorphism
All methods in the interface must be overridden i.e they should be implemented, we don’t use override keyword, but just we implement it.
 Only methods declared with abstract key will be overridden. Because abstract class may or may not contain abstract methods. Non abstract members will have an implementation in abstract class itself.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast

 
Properties

A property is a member that provides a flexible mechanism to read, write, or compute the value of a field.

Fields should (almost always) be kept private to a class and accessed via special methods called accessors(get and set properties). 

public class MyClass
{
   // This is a field.  It is private to your class and stores the actual data.
   private string _myField;
 
   // This is a property. When you access it uses the underlying field
   public string MyField
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }
}

We can create read-only and write-only properties.

   // Read only Property
   public string MyField
    {
        get
        {
            return _myField;
        }
    }

   // write only property
   public string MyField
    {
        set
        {
            _myField = value;
        }
    }
 
Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields.

// Restricting value of field using set accessor.
public class Date
{
    private int month = 7; 
 
    public int Month
    {
        get
        {
            return month;
        }
        set
        {
            if ((value > 0) && (value < 13))
            {
                month = value;
            }
        }
    }
}

 

 

1 comment:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    c-net training in electronic city

    ReplyDelete