Friday, 2 August 2013

DOTNET C# PROGRAMMING INTRODUCTION TUTORIAL INTRODUCTION K MANOHAR GOUD

9866550012
DOTNET C# PROGRAMMING INTRODUCTION TUTORIAL 

C# (CSHARP) is intended to be a simple, modern, general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 5.0, which was released on August 15, 2012.

Design Goals of c# (CSHARP)

  • The C# language is intended to be a simple, modern, general-purpose, object-oriented programming language.
  • The language, and implementations thereof, should provide support for software engineering principles such as strong type checking, array bounds checking, detection of attempts to use uninitialized variables, and automatic garbage collection. Software robustness, durability, and programmer productivity are important.
  • The language is intended for use in developing software components suitable for deployment in distributed environments.
  • Source code portability is very important, as is programmer portability, especially for those programmers already familiar with C and C++.
  • Support for internationalization is very important.
  • C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that use sophisticated operating systems, down to the very small having dedicated functions.
  • Although C# applications are intended to be economical with regard to memory and processing power requirements, the language was not intended to compete directly on performance and size with C or assembly language.

C# has the following syntax:
  • Semicolons are used to denote the end of a statement.
  • Curly braces are used to group statements. Statements are commonly grouped into methods (functions), methods into classes, and classes into namespaces.
  • Variables are assigned using an equals sign, but compared using two consecutive equals signs.
  • Square brackets are used with arrays, both to declare them and to get a value at a given index in one of them.

Summary of versions
C# 2.0C# 3.0C# 4.0C# 5.0 Future
Features
added
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
  • Dynamic binding
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types ("NoPIA")
  • Asynchronous methods
  • Caller info attributes
  • Compiler-as-a-service("Roslyn")
  • Community technology preview as of September 2012


Saturday, 27 July 2013

DOTNET C# PROGRAMMING TUTORIAL INTRODUCTION K MANOHAR GOUD

9866550012
DOTNET C# PROGRAMMING TUTORIAL 

C# was created by Microsoft as a major part of its .NET initiative. C# is a modern, powerful, component-orientated, flexible, safe, internet friendly and an easy to use language that takes advantage of virtually any feature in this platform. 
Introducing C# 
 
With the release of Visual Studio (formerly codenamed Whidbey), C# is back with some new innovations. Besides Generic types, the C# language introduces some other interesting features such as Iterators, Partial Classes and Anonymous methods, which are briefly mentioned below.
Generics
Although new to the .NET platform, this concept has been around for years. Generics is a term used to describe generic types. It greatly enhances application performance and type safety and allows you to write highly general, flexible and safe code. It permits classes, interfaces, structs, delegates and methods to be parameterized by the types of data they store and manipulate.
Iterators
Iterators specify how a for-each loop will iterate over a collection and return its internal items. They allow you to create enumerable classes with minimum coding.
Partial Classes
Partial Classes allows you to split a single type, like your class, across more than one file (.cs). They are useful if you have extremely large, unwieldy types.
Nullable Types
Nullable types allow a variable to contain a value that is undefined. This is useful when working with databases where the value returned might be null
Anonymous Methods
Anonymous Methods Are Inline Delegates. It enables you to pass a block of code as a parameter. Anonymous methods enables you to directly associate a block of code statements to a given event. You use them anywhere a delegate is used . So there is no need to define a new method.
Namespace alias qualifier
C#  adds the namespace alias qualifier, the :: operator, to provide more control over accessing namespace members.
Static Classes
With C#, now you also can declare classes as static. This signals the compiler that this class should not be instantiated and can only contains static members.
Property Accessor Accessibility
C#  allows a fine control over the accessibility of accessors and indexers within a property.
Covariance and Contravariance in Delegates
The method passed to a delegate may now have greater flexibility in its return type and parameters.
Generics
 
Classes are templates that you can use to build new objects. Generics are templates that you can use to build new classes. This code template can be applied to use the same code repeatedly. A generic class is tied to one or more specific data types.
Generics permit classes, interfaces, structs, delegates and methods to be parameterized by the types of data they store and manipulate. They are Type-independent algorithms and collections. They enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generics are defined with left and right brackets: <T>. Here ‘T’ in <T> is the name of the type that is going to be used.
Let me demonstrate the use of Generics by taking a simple example:
namespace GenericsDemo
{
    class TestGenerics
    {      
                static void Main(string[] args)
                 {
 
      GenericsExample();
}   
 
     private void GenericsExample()
      {
            ClsGeneric<int> intGeneric = new ClsGeneric<int>(1000);
ClsGeneric<string> strGeneric = new ClsGeneric<string>("Voila");
            ClsGeneric<float> fGeneric = new ClsGeneric<float>(23.38f);
ClsGeneric<double> dGeneric = new ClsGeneric<double>(444.4);
            ClsGeneric<bool> bGeneric = new ClsGeneric<bool>(true);
 
      }
    }
 
    public class ClsGeneric<T>
    {
        public ClsGeneric(T Type)
        {
Console.WriteLine("T over here is {0} ", typeof(T).ToString());
        }
    }
}
By using a generic type parameter T, you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.
Iterators
 
In the earlier versions of C#, in order to use the for-each loop, you need to implement the IEnumerableinterface which in turn demands the implementation of the GetEnumerator() method. This method returns an IEnumerator object using which you can use the foreach loop.
An iterator on the other hand, enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface.
Let me demonstrate this with an example :
public class StringCollection : System.Collections.IEnumerable
{
    string[] names = { "Tom", "Dick", "Harry”, "Ralph", "Jack", "Jill” };
 
    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < names.Length; i++)
        {
            yield return names[i];
          // In C#1.x you would have specified it using
          // return names[i].GetEnumerator();
        }
    }
}
 
class TestStringCollection
{
    static void Main()
    {
        // Create an instance
        StringCollection strNames = new StringCollection();
 
        foreach (string name in strNames)
        {
            System.Console.WriteLine(name);
        }
Console.WriteLine("Press any key to continue...");
      Console.ReadKey();
    }
}
 
Partial Classes
 
C#  introduces the concept of partial type definitions for classes, structs, and interfaces that allows you to define a C# type across multiple *.cs files. This leads to easier maintenance and development as more than one developer can simultaneously write the code for the class.
public partial class A
{
          public void methodA()
          {
                   // Code for methodA
}
}
 
public partial class A
{
          public void methodB()
          {
                   // Code for methodB
          }
}
Nullable Types
 
A type is said to be nullable if it can be assigned a value or can be assigned a null reference. This change makes it easier to integrate with databases, especially for fields that are optional.
A null type is very similar to its equivalent non-nullable type. The difference lies in how it is declared. For example : To declare an integer, you would declare it like this :
int iVal = 1; 
However in order to enable iVal to store a null value, you will declare it like this :
int? iVal = 1;
 
Now the way to define any valuetype as a nullable type is to define the generic System.Nullable<T> type. So the syntax to define a nullable integer is:
System.Nullable<int> iVal;

However this is somewhat difficult to read and that is why C#
provides a cleaner syntax for the nullable type by adding a
question mark to the immediate right of the type name when
defining a variable. The Syntax is [Value-Type]?
So System.Nullable<int> iVal and int? iVal are equivalent. 
Similarly you can also assign it a value null and use the HasValue and Value read-only properties to test for null and retrieve the value. Here’s an example :
int? iVal = null;
if (iVal.HasValue == true)
{
      System.Console.WriteLine("iVal = " + iVal.Value);
}
 else
 {
      System.Console.WriteLine("iVal = Null");
 }
Anonymous Methods
 
Anonymous methods help you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. This construct allows you to directly associate a block of code statements to a given event. In general, you can use anonymous methods anywhere you can use a delegate. An anonymous method consists of the keyword delegate, an optional parameter list, and a statement list enclosed in { and } delimiters. In some cases, the anonymous methods can omit the parameter list.
public class frmOld : Form
{
 // This method connects the event handler.
 public frmOld()
 {
    InitializeComponent();
    btnOld.Click += new EventHandler(ButtonClick);
 }
 
 // This is the event handling method.
 private void ButtonClick(object sender, EventArgs e)
 {
    MessageBox.Show("Old method of handling ButtonClick");
 }
}
Using Anonymous methods :
public class frmNew : Form
{
 public frmNew()
 {
    InitializeComponent();
 
    btnNew.Click += delegate(object sender, EventArgs e)
    {
 
MessageBox.Show(“New way of handling button click using anonymous methods");
    };
 }
}
// Declare a delegate
delegate void PrintHello(string str);
 
class TestAnonymous
{
    static void Main()
    {
          hello = new PrintHello(TestAnonymous.TestMethod);
Without anonymous method you would associate the delegate with a named method. For eg:
 
hello = new PrintHello(TestAnonymous.TestMethod);
 
//and declared a method to associate it with the named delegate
 
 
static void TestMethod(string test)
{
   System.Console.WriteLine(test);
}
 
Static Classes
Static classes are classes that contain only static members. These static members can be initialized only by using static constructors. The data and functions that these classes create, can be accessed without creating an instance of the class. Static classes are sealed so they can not be inherited. TheSystem.Math class is an example of this construct.
Static classes can be used when there is no data or behavior in the class that depends on object identity. One of the advantages of static classes is improved performance. Since there is no instantiation of object, the framework maintains a single object in memory for static members. They are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Creating a static class is much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. Lets see an example of a static class. 
 
Property Accessor Accessibility
 
Properties provide flexibility to read and write the values of private fields. They can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
In C# 1.x, we declare a property in our class in the following manner:
    class ClsProp
    {
        private string strMyName = "Suprotim";
 
        public string StrMyName
        {
            get { return strMyName; }
            set { strMyName = value; }
        }
    }
Here the ‘get’ and the ‘set’ accessors have the same accessibility level i.e., they are both ‘public’ as the property itself is ‘public’. However, it is sometimes useful to restrict access to one of these accessors, which was not possible for us in C# 1.x.
In C# 2.0, this has changed :
public string StrMyName
{
    get
    {
        return strMyName;
    }
    protected set
    {
        strMyName = value;
    }
}
 
In this example, a property called StrMyName defines a get and set accessor. The get accessor receives the accessibility level of the property itself, public in this case, while the set accessor is explicitly restricted by applying the protected access modifier to the accessor itself.
Note : This feature of having Accessor Accessibility was provided in C# v1.0 beta. However Microsoft removed it before the C# v1.0 RTM as they felt it was too complicated for developers. In C# 2.0, it has been re-introduced.
Covariance and Contravariance
 
In .NET 1.1, delegates could only be created with methods whose arguments strictly matched the signature of that delegate. With .NET 2.0, Covariance and contravariance provide a degree of flexibility when matching delegate methods with delegate signatures.