Saturday, 7 May 2011

Use of Operators, Types and Variables in C#






  • Operators, types and variables in C#:-
    Variables- A variable is a storage location with a type. 






  • Variables can have values assigned to them, and those values can be changed programmatically.

       A constant is a variable whose value cannot be changed.
    Types-   Like C++ and Java, C# divides types into two sets:   



  • intrinsic Built-in types that the language offers and 



  • user-defined types that the programmer defines.






  • C# also divides the set of types into two other categories: 



  • value types and reference types. 



  • The principal difference between value and reference types is the manner in which their values are stored in memory. 






  • C# is a "Strongly Typed" language.



  • Thus all operations on variables are performed with consideration of what the variable's "Type" is. 



  • There are rules that define what operations are legal in order to maintain the integrity of the data 



  • you put in a variable.
    The Boolean Type
       Boolean types are declared using the keyword, bool. 






  • They have two values: true or false. In other languages, such as C and C++, 



  • boolean conditions can be satisfied where 0 means false and anything else means true.



  • However, in C# the only values that satisfy a boolean condition is true and false, which are official keywords.
    
        using System;
    
        class Booleans
        {
            public static void Main()
            {
                bool content = true;
                bool noContent = false;
    
                Console.WriteLine("{0} C# programming language content.", content);
                Console.WriteLine("This is second statement {0}.", noContent);
            }
        } 
    Integral Types
      In C#, an integral is a category of types. For anyone confused because the word Integral sounds like a mathematical term, from the perspective of C# programming, these are actually defined as Integral types in the C# programming language specification. They are whole numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as defined by the Unicode Standard.
    Floating Point and Decimal Types
    A C# floating point type is either a float or double. They are used any time you need to represent a real number. Decimal types should be used when representing financial or money values.
    The string Type
    A string is a sequence of text characters. You typically create a string with a string literal, enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1, where we used the Console.WriteLine method to send output to the console.
    The Array Type
    Another data type is the Array, which can be thought of as a container that has a list of storage locations for a specified type. When declaring an Array, specify the type, name, dimensions, and size.
    
        using System;
    
        class NewArray
        {
            public static void Main()
            {
                int[] myInts = { 5, 10, 15 };
                bool[][] myBools = new bool[2][];
                myBools[0] = new bool[2];
                myBools[1] = new bool[1];
                double[,] myDoubles = new double[2, 2];
                string[] myStrings = new string[3];
    
                Console.WriteLine("myInts[0]: {0}, myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1], myInts[2]);
    
                myBools[0][0] = true;
                myBools[0][1] = false;
                myBools[1][0] = true;
                Console.WriteLine("myBools[0][0]: {0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
    
                myDoubles[0, 0] = 4.245;
                myDoubles[0, 1] = 6.355;
                myDoubles[1, 1] = 8.415;
                myDoubles[1, 0] = 56.1148917;
                Console.WriteLine("myDoubles[0, 0]: {0}, myDoubles[1, 0]: {1}", myDoubles[0, 0], myDoubles[1, 0]);
    
                myStrings[0] = "An";
                myStrings[1] = "App";
                myStrings[2] = "Cattt";
                Console.WriteLine("myStrings[0]: {0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0], 
    myStrings[1], myStrings[2]);
    
            }
        } 






  • Concepts about Namespaces in C#

    Namespace in C#.
    Namespaces group related classes and types, and they define categories in which we can include any new class that provides related functionality.
    
    namespace MyCompany.r4r 
    {
        class MyClass 
        {
      // some code here
        }
    }
    
    namespace MyCompany.r4r
    {
        class MyClass1 
        {
      // some code here
        }
    }
    Classes and Object in C#.

  • Defining Classes:-  To define a new type or class, first declare it, and then define its methods and fields. Declare a class using the class keyword.    The complete syntax is as follows:  [attributes] [access-modifiers] class identifier [:base-class]
          {
             class-body
          }

  • For Example.
    
    public class Test
              {
                 public static int Main( )
                    {
                                      
      Console.Writeline("This is Class");     
      }
              }
    Defining Object:-
  •   A distinction is drawn between value types and reference types. The primitive C# types (int, char, etc.) are value types, and are created on
    the stack. Objects, however, are reference types, and are created on the heap, using the keyword new, as in the following:   
                   
               
    
       Test t = new Test();

              t
    does not actually contain the value for the test class object; it contains the address of that (unnamed) object that is created on the heap. t  itself is just a reference to that object.
    How to create a program in C#?
    Step 1: Start notepad from Start -> Program Files -> Accessories -> Notepad so that you can write the HelloWorld program. The program you write in C# is also called as source code.
    Step 2: Write the HelloWorld program, you can either type the program shown below into notepad or just copy-paste it from here-
    
    public class Helloworld
    
               {
    
                   public static void Main()  
    
                    { 
    
                          System.Console.WriteLine("you are welcome in world of C#");             
    
                    }
    
               }

    Step 3: Once you have finished typing your program you should Save the source code file. In fact after making any changes to your source code, you should always save the  file. To save the file for the first time in notepad click on File menu -> Save As. In the Save As dialog select the directory from the Save In dropdown where you want to save your files, I generally save my files to C:\csharp, and then in the File name textbox, enter the file name as HelloWorld.cs (although you can provide any name you want but it should have an extension.cs). and click Save. Once you have saved the
    source code, and if you make any further modifications, in notepad use the Ctrl+S keyboard short-cut to save your source code file.
    Step 4: Since you have finished writing the source code its time to compile it. Since we are using a command-line compiler that ships with the .NET SDK, start the command prompt from Start -> Program Files -> Accessories -> Command Prompt. Or go to Start -> Run, type cmd and press enter. Now from the command prompt navigate to the directory where you have stored the source code file by issuing the following DOS commands.cd\ -To navigate to the root of the derived csharp - To navigate to the csharp directory. Once you are in the csharp directory where you
    saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the following command to compile our HelloWorld.cs
    program:csc HelloWorld.cs
    Step 5: If the compilation of the source code was successful then a new executable (Exe) file by the name HelloWorld.exe will be created in the directory you compiled the source code. To execute the program simply type the name of the executable file at the command prompt.
    Points to Remember

  •  C# code can be written in any text editor like notepad.

  •  C# Source Code files are saved with the extension.cs.

  •  C# is a case-sensitive language so you have to be careful while typing.

  •  C# runs on the .NET Platform, hence you need to install the .NET SDK in order to compile C# programs.

  •  The C# compiler is contained within the file csc.exe, which generally   
    resides in the C:\windows\Microsoft. NET\Framework\v1.0.4322 directory.

  • Comparison between other Programming Languages

    Similarity and difference with C/C++
      C# is directly related to C and C++, C++ is a superset of C. C and C++ shares several syntax, library and functionality. In addition structures, unions, arrays, strings and pointers are most important and similar functionality for both languages.
      C# inherits most of its operators, keywords, and statements directly from C++. Enums are clearly a meaningful concept in C++.
    Finally I can clearly say that C# is the first component-oriented language in the C/C++ family.
       C# constructors are verisimilar with C++ constructors. Like C++, methods are non-virtual by default, but can be marked as virtual.

       There is also some difference between C# and C++, C# supports multiple inheritance of interfaces, but not of classes. Another difference is destructors, their syntax is same with C++ but actually they are very different.
     
    Difference between C# and VB
    C# allows 'unsafe' code, or pointer manipulation. VB allows methods with optional parameters.
    C# allows assignments embedded in expressions (e.g., if ((x = y.Value) == 2)).VB allows types within interfaces.
    C# has anonymous methods.VB has the very flexible Select construct (much more flexible than the C# switch).
    C# has the useful conditional ternary operator (?:). The VB If function is not a good substitute since the arguments must all be evaluated. VB has the When filter for catch block headers (no equivalent exists in C#).
    Difference between C# and Java
    Features of C# not present in Java
    C# provides integration with COM.
    C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods.
    C# has the ability to alias namespaces.
    C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
    C# implements properties as part of the language syntax.
    C# allows switch statements to operate on strings.

    Data Types in C#

    C# DataTypes

    Data Types means what type of data a variable can hold . C# is a strongly typed language, therefore every variable and object must have a declared type. The C# type system contains three Type categories.
          Value Types
          Reference Types
          Pointer Types
      In C# it is possible to convert a value of one type into a value of another type . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing .
    Ex.    int month;
                     int : is the data type
                     month: is the variable name
    int
    int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
    C# Runtime type : System.Int32
    C# declaration : int month;
    C# Initialization : month = 10;
    C# default initialization value : 0
    decimal
    Decimal is of a 128-bit data type.The approximate range and precision for the decimal type are -1.0 X 10-28 to 7.9 X 1028
    C# Runtime type : System.Decimal
    C# declaration : decimal val;
    C# Initialization : val = 0.12;
    C# default initialization value : 0.0M
    string
    Represents a string of Unicode characters. string variables are stored any number of alphabetic,numerical, and special characters .
    C# Runtime type : System.String
    C# declaration : string str;
    C# Initialization : str = ".Net Environment";
    bool
    Bool is used to declare variables to store the Boolean values, true and false. In C# , there is no conversion between the bool type and other types.
    C# Runtime type : System.Boolean
    C# declaration : bool flag;
    C# Initialization : flag = true;
    C# default initialization value : false
             The following list shows the list of data types available in C# and their corresponding class/struct in .NET class library.

    # Data type Mapped to .NET class/struct
    sbyte System.SByte
    byte System.Byte
    char System.Char
    float System.Single
    decimal System.Decimal
    double System.Double
    ushort System.UInt16
    short System.Int16
    uint System.UInt32
    int System.Int32
    ulong System.UInt64
    long System.Int64
    bool System.Boolean
    string System.String
    object System.Object

    Boxing:
    Converting value types to reference types is also known as boxing. As can be seen in the example below, it is not necessary to tell the
    compiler an Int32 is boxed to an object, because it takes care of this itself.
    e.g.-   Int32 a = 10;
                object count = a ; // Implicit boxing
                Console.WriteLine("The Object count = {0}",count); // prints out 10
                  //However, an Int32 can always be explicitly boxed like this:
                 Int32 a = 10;
                 object count = (object) a; // Explicit boxing
                 Console.WriteLine("The object count = {0}",count); // prints out 10

    Unboxing: The following example intends to show how to unbox a reference type back to a value type. First an Int32 is boxed to an object, and then it is
    unboxed again. Note that unboxing requires explicit cast.
    Ex.      Int32 a = 5;
                       object count = a; // Implicit
                       Boxing a = (int)count; // Explicit Unboxing
     

    Type Conversions  Conversion is based on type compatibility and data compatibility.
    1. Implicit Conversion

    2. Explicit Conversion

    Implicit Conversion   In implicit conversion the compiler will make conversion for us without asking.

    char -> int -> float is an example of data compatibility.
     

    
    using System;
    class Program
        {
            static void Main(string[] args)
            {
                int x =10000;
                int y =20000;
                long total;
                // In this the int values are implicitly converted to long data type;
                //you need not to tell compiler to do the conversion, it automatically does.
                total = x + y;
                Console.WriteLine("Total is : " + total);
                Console.ReadLine();
            }
        }
    Explicit Conversion
        In explicit conversion we specifically ask the compiler to convert the value into another data type.  CLR checks for data compatibility at runtime.
     

    
    using System;
    class Program
       {
          static void Main(string[] args)
           {
              int x = 65; 
              char value;
              value = (char)x;
                // In this the int values are explicitly converted to char data type;
                //you have to tell compiler to do the conversion, it uses casting.
                Console.WriteLine("Value is: " + value);
                Console.ReadLine();
            }
        }

    Microsoft .NET provides three ways of type conversion:

    1. Parsing
    2. Convert Class
    3. Explicit Cast Operator ()
     

    Parsing
    Parsing is used to convert string type data to primitive value type. For this we use parse methods with value types.
     

    
    using System;
    class Program
      {
       static void Main(string[] args)
        {
               //using parsing
                int number;
                float weight;
                Console.Write("Enter any number : ");
                number = int.Parse(Console.ReadLine());
                Console.Write("Enter your weight : ");
                weight = float.Parse(Console.ReadLine());
                Console.WriteLine("You have entered : " + number);
                Console.WriteLine("You weight is : " + weight);
                Console.ReadLine();
        }
       }
    Convert Class
    Convert class contains different static methods like ToInt32(), ToInt16(), ToString(), ToDateTime() etc used in type conversion.
     

    
    using System;
       class Program
        {
            static void Main(string[] args)
            {
                // example of using convert class
                 string num = "23";
                int number = Convert.ToInt32(num);
                int age = 24;
                string vote = Convert.ToString(age);
                Console.WriteLine("Your number is : " + number);
                Console.WriteLine("Your voting age is : " + age);
                Console.ReadLine();
            }
        }

    Explicit Cast Operator ()
    It can used with any type having type compatibility and data type compatibility.
     

    
    using System;
        class Program
        {
            static void Main(string[] args)
            {
                int num1, num2;
                float avg;
                num1 = 10;
                num2 = 21;
                avg = (float)(num1 + num2) / 2;
                Console.WriteLine("average is : " + avg);
                Console.ReadLine();
            }
        }

    .Net Frameworks Architecture

    .Net is not an Operating System. It is a IDE. It provides some functionality for the programmers to build their solution in the most constructive and intelligent way ever.  Just to tell you the truth, most of the codes in .Net environment resembles with the JAVA coding as if some people coming from Java would find it as to their native language.

      .NET is a Framework that loads into your operating system, which you need not to load in the later versions of windows like Windows 2003 server or Just a new release of Windows Vista. As it is going to be added as a component in the next generation of windows.

       Now, What is the .Net all about? Well, Its a framework that supports Common Language Runtime (CLR). As the name suggests, Common Language Runtime will be something that will run a native code for all the programming languages provided within the Architecture.

        Another feature of .net is language independence, to tell you about language Independence, .Net is not at all efficient in that. Just Microsoft built their own version of languages like C++, J# (for Java), C#, VB etc that can communicate between each other.
    After all J#, even if they resembles with JAVA is not purely Java.. Thus, the word may look to you somewhat fake. Now what is the most prospective part of .NET? Now, with the growing Internet, ASP. NET may be the most important part of .NET technology. Well, ASP. NET has a new technology where the controls reside server side. You don't bother to use traditional client side controls.
    In .NET technology as there is a provision of runtime building of machine codes, a web server can directly compile and transmit codes to the browser during runtime. This is , I think the most approved and widely accepted part of .NET.
    NEW things of .NET? well, during the last two years , Microsoft is constantly changing the .NET technology, that may not be good for a settled programmer. Well, first of all, in .NET 2003 Microsoft changed some features and also adds some new things.
    Well, new things are good, but changing the existing in such a quick succession is not at all good from programmers point of view. Again, in 2005, Microsoft publishes the new release of VISUAL STUDIO.NET 8 .
    This is a completely new environment. It have new releases of controls, the IDE is also different. That's not what we all wanted as a programmer. What do you say?

      Now, Microsoft is also increasing its scope.. One of the most important feature that is just now introduced is AJAX. Well, the name is what can be said as Asynchronous Java Script with XML.

    Introduction to C#

    What is C# ?

    C# is intended to be a simple, modern, general-purpose, object-oriented programming language.
     The most recent version is C# 4.0, which was released on April 12, 2010.

    C# (pronounced "see sharp") is a multi-paradigm programming language encompassing imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within the .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed for the Common Language Infrastructure.

    Features of C#

    Some notable distinguishing features of C# are:

  • There are no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.

  • Managed memory cannot be explicitly freed instead, it is automatically garbage collected.

  • Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory which is no longer needed.

  • In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block.

  • Multiple inheritance  is not supported by C#, although a class can implement any number of interfaces.

  •