Wednesday, 23 May 2012

IComparable Interface in c#

Sort by Price list;

Step 1)  Create console Application
Step 2) Add class called Stocks.cs  and implement IComparable interface

fileName: Stocks.cs

using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// Summary description for Stocks
/// </summary>
public class Stocks : IComparable
    public String Symbol;
    public decimal price;
    public DateTime dtPrice;

    public int CompareTo(object obj)
        if (obj == null) return 1;
        Stocks st = obj as Stocks;
        return this.price.CompareTo(st.price);

Step 3)  in Program.cs
             1)  Initialize array of objects(i.e stocks)
              2) display without sorting
             3) display after sorting

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)

            Stocks[] stockList =
        new Stocks{Symbol="IBM", price=88.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="CSCO", price=22.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},
        new Stocks{Symbol="INTL", price=32.80M, dtPrice=new System.DateTime(2012,6,26,9,00,00)},

            Console.WriteLine("Before Sort ......");
            foreach (Stocks s in stockList)


            Array.Sort(stockList); //sort arrays ,icomparable compare function will be called.

            Console.WriteLine("After Sort ......");
            foreach (Stocks s in stockList)
                Console.Write("Symbol={0},rate={1},date={2}", s.Symbol, s.price, s.dtPrice);




Saturday, 19 May 2012

Nullable types in .net

Nullable types in .net
Provides null values to value types(int,float,double,struct,enum)

int? i=null;  <==>  System.Nullable<int> i = null;
Integer i has all properties of default integer in addition to null value.

Partial classes in C#

Partial Classes in C#--> Partially define some methods in one file , add new methods to a class in another file, as shown below. it can be applied to class, struct or interface.

keyword: partial


namespace ConsoleApplication5
    public partial class Person
        int Age;
        string Name;
        public Person(int age, string n)
            Age = age;
            Name = n;

        public bool isEligible() { if (Age > 18) return true; else return false; }
namespace ConsoleApplication5
     public partial class Person
         int pin;
         public Person(int p)
             pin = p;
         public bool isPinValid()
             if (pin >100000 && pin > 999999) return false;
             else return true;

Program.cs(application Main file)

namespace ConsoleApplication5
    class Program
        static void Main(string[] args)
            Person p = new Person(20,"sitapati");

Delegates in C#

Delegates are reference types in C# , which holds address of a method(s).
Single cast delegate which holds address of single method.
Multicast cast delegate which holds address of multiple methods. return type is last method in the invocation list.

By default all delegates are derived from System.Delegate.

Delegate can be instance type/static.  If delegate is instance type,System.Delegate Target property holds address of the methods ,if it is static System.Delegate  Target  property  is null.

Delegate Example
delegate bool checkEven(int x); //delegate declaration: delegates references a method return bool  and takes int as input param.

namespace ConsoleApplication
    public class Program1
        delegate bool checkEven(int x);
        public static void Main()
            checkEven even = isEven; //instantiate delegate & assign method address to delegate
            //calling delegate, is nothing but calling method indirectly;
            bool b = even(10);

             b = even(9);

//delegate target
Console.WriteLine(even.Target); //null because delegate pointing/referencing to static method
        static bool isEven(int x)
               return (((x%2)==0)?true:false);


Note: delegates can be part of namespace/within class member, but not within a function body.

Delegates Versus Interfaces
public interface Icalculator
  int Add(int x,int y);

public class CalService:Icalculator
        int  Add(int x,int y)
                  return x+y;

delegate int myDel(int x,int y);
public static void Main()
         CalService cService = new CalService();
         Console.WriteLine("With Interface the value is {0}",cService.Add(10,20));

          //with delegates
            myDel del= new myDel(Addnum);
   COnsole.WriteLine("With Delegates value is={0}",del(10,20));

static int Addnum(int x,int y)
 return x+y;

Note:Whatever u can do with delegates, samething can be done with interfaces, but every class must implement that interface. 2)This will only work with single method(i.e multicast environment it will not work).

Contravariance & Covariance in delegates.

delegate void StringDel(String str);

            StringDel sdel = new StringDel(Print);
        static void Print(object o)
            Console.WriteLine(o); //in this case object o up-casted to string type.

     delegate object covardemo();
        covardemo cd= new covardemo(getString);
static string getString(){return "Hello";}
In this case delegate expects return type as object, but gets string this is called covariance.

Anonymous Types in C#

Anonymous Types are set of public properties without including types explicitly,they are read-only in C#.
They must be declared with var keyword. All properties must be initialized.

Example 1
var objAnyo= new { Name = "seethapathi", Age = 28, city = "Hyderabad", Country = "INDIA" };

Console.WriteLine( objAnyo .Age.GetType()); //returns System.Int32
Console.WriteLine( objAnyo .Name.GetType()); //returns System.String etc.,

type of the variables are determined at compile time itself. var keyword tells the compiler to use "type inference(automatic detection of type)".

objAnyo .Age = 31;

gives compiler error

 Error 1 Property or indexer ' objAnyo  #1.Age' cannot be assigned to -- it is read only c:\users\administrator\documents\visual studio 2010\Projects\ConsoleApplication4\ConsoleApplication4\Program.cs 15 13

Example 2
  Anonymous types are useful in LINQ

var customer =  from c in  customers
                            select new {c.CustomerID,c.City}

here c.CustomerID,c.City  are 2 properties for anonymous type customers.
c.CustomerID,c.City types  are same as in customers

Note: returning subset of elements(as shown in Example 2) is also called anonymous types.

Friday, 18 May 2012

Anatomy of Console Application in C#

Step 1)  Create Console Application as shown below
Step 2) Following Directories and Files will be created.
       1)  Solution file: ConsoleApplication4.sln
       2) Project file ConsoleApplication4.csproj
                 1)Properties folder 
                       AssemblyInfo.cs --> contains meta data of the assembly, such as name,version,security etc.,
                 2) References
                       Microsoft.CSharp-> contains classes to support compilation & code generation
                       System  --> Core types ,base classes,interfaces,event handlers etc.,
                       System.Core -> collections,Io support,threading,security etc.,
                       System.Data --> database access support
                       System.Data.DataSetExtensions-> Dataset to LINQ support
                       System.Xml --> xml support
                       System.Xml.Linq --> xml to LINQ support

Step 3)  Build the solution

Step 4) Go to application folder
  in this case : C:\Users\Administrator\Documents\visual studio 2010\Projects\ConsoleApplication4\ConsoleApplication4

After building  2 folders will be created
1) bin --> actual binaries store in this folder
2)obj --> supporting binaries are stored in this folder.

ConsoleApplication4.csproj  project file for this assembly
program.cs --> applictaion log file

Now go to BIN directory  , 1 or 2 folders will exists
  in this case  debug folder--> click on it

  1. It has  4 files  1.ConsoleApplication4.exe  --> actual binary file or MSIL code
  2. ConsoleApplication4.pdb  --> program database file
  3. ConsoleApplication4.vhost.exe --> clr host for the ConsoleApplictaion4.exe ,this is unmanaged application
  4. ConsoleApplication4.vhost.exe.manifest

Sunday, 13 May 2012

Reflection in C# 4.0

Serialization in C# 4.0

Collections in C# 4.0

In C# Collections are in-built data structures,to store & Retrieve structural information. It is classified into generic & non-generics.
In non-generic all types will return as object class, need to type cast it to appropriate type. So non-generic collections are weakly typed.

in Generics appropriate type will be given at compile time, all objects return same type not object type, so it is strongly typed.

Non-Generic Collections included in  System.Collections Namespace
Generics included in System.Collections.Generic.

Generic Collections

  1. List<T>
  2. Stack<T> & Queue<T>
  3. Dictionary<TKey,TValue>
  4. HashSet<T>
  5. LinkedList<T>


public class Stocks
  public string Symbol{get;set;}
  public decimal price{get;set;}
 public DateTime dt{get;set;}

Create list of Stock objects.

List<Stocks> stockList = new List<Stocks>();

Insert Items into List

            stockList.Add(new Stocks{ dt=System.DateTime.Now,Symbol="CSCO", price=22.23M});
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "MSFT", price = 28.99M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "IBM", price = 88.90M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "FB", price = 22.23M });
            stockList.Add(new Stocks { dt = System.DateTime.Now, Symbol = "GooG", price = 580.97M });

Capacity of List class stockList: Initial is 4, there after it will be incremented by 4.
so stockList capacity is  8.

Trim stockList capacity to 5 i.e trim to number of elements in the List by calling
stockList.TrimExcess();  //output would be 5 otherwise 8.

List to Array Conversion

Access List Elements by Index

                for(int i=0; i < stockList.Count;i++)
                Stocks firstElement = stockList[i];
                Console.WriteLine("Symbol={0},price={1},date={2}", firstElement.Symbol, firstElement.price, firstElement.dt);
            catch (IndexOutOfRangeException ex)

Find Stock based on Field.i.e Symbol
            bool exists=stockList.Exists(s => s.Symbol == "IBM");
            Console.WriteLine("is IBM Stock  exists={0}",exists);

Tuesday, 8 May 2012

Classes in C#

Classes are data structures in C#. Its a blue print for an object.It has  Set of methods, properties are wrapped into a unit called Class.
or General Perception  making into a programmable unit called class.

for ex:
                 class Person
                         //Set of properties
                           String Name;
                           int Age;
                           String Color;
                           float weight;
                       //Set of methods
                      public string getPersonName(){return Name;}
                      public int getPersonAge(){return Age;}
                      public float getPersonWeight(){return weight;}
                      public string getPersonColor(){return Color;}

                      public string setPersonName(string Name){this.Name = Name;}
                      public int setPersonAge(int Age){this.Age=Age;}
                      public float setPersonWeight(int weight){this.weight=weight;}
                      public string setPersonColor(string Color){this.Color=Color;}

Indexers in C#--  Its a property in a class.class can be indexed like an array.
                 class indexDemo
                   int[] arr= new int[100];
                   public int this[int index]
                               return arr[index];
                     set { arr[index] = value; }

indexDemocs1  cs1 = new  indexDemo ();
            cs1[0] = 1;
            cs1[1] = 2;
            for (int i = 0; i < 100; i++)
       There is no way user can find upper bound, so index more than 100 will throw "IndexOutOfRangeException"

Abstract Classes vs Interfaces

Abstract Classes    vs Interfaces
Abstract classes is a class cannot be instantiated & must be implement by sub classes. 
   1) Class can have some methods are implemented
   2) Class can have some methods are abstract
   3)  Class can have some methods implemented & remaining are abstract .

A concrete class can inherit only one Abstract class. (Because .NET programming languages doesn't support multiple inheritance).

               Its a contract all methods are virtual. No Implementation provided.  
A class must implement all methods.

Once Interface published, User cannot change it. i.e adding new methods/deleting methods/modifying  existing method signatures.  Its like a blackbox. 

A class can implement multiple interfaces. A class cannot implement multiple classes.

Interfaces share common functionality among classes. Interfaces are generic. 
Abstract classes are not , This is specific to context/concept.

Any method  accepts  interface as a param, the class(es) implemented those interfaces can be passed as an argument.  Its up-to the programmer to cast it to appropriate type.

Any method accepts abstract class as an argument, any derived class can be passed as an argument.

So Abstract classes support versioning ,because user can add new method implementations without breaking the clients. This  is not possible with interfaces, in this case new interface should be created/derived from existing interface.

  abstract  class   Machine
            void method1()
      abstract void Method2();

interface ICal
          long Add(long a,long b);
          long Sub(long a,long b);
          long Mul(long a,long b);
          long Div(long a,long b);

Abstract classes only contain abstract methods and abstract properties.
Interfaces can contain methods, properties, events or indexers. 

Sunday, 6 May 2012

Connect to Excel using ODBC in C#

Step1 )
                  Create Excel  file with this

2)  Select Entire List and name it as "MyProgrammingList"
3)  Save to some folder for ex: c:\excelone\progstats.xls.

Step 2)   Create  Data Source Name(DSN)

      Control Panel\All Control Panel Items\Administrative Tools\DataSources(ODBC)

Click FINISH button to add DSN

Step 3)   Create   ASP.NET   Web Site.
             in Default.aspx  page    add Grid View Control

    <form id="form1" runat="server">
    <asp:gridview ID="Gridview1" runat="server"></asp:gridview>

In  Code Page
add name spaces

using System.Data.Odbc;
using System.Data;

        protected void Page_Load(object sender, EventArgs e)
            System.Data.Odbc.OdbcConnection conn =
                new OdbcConnection("DSN=myExcelone");  //DSN created in Step 2

            OdbcDataAdapter ad = new OdbcDataAdapter("select * from MyProgrammingList", conn);
            //MyProgrammingList  named for group of cloumns in Excel Sheet.
            DataSet ds = new DataSet();
            Gridview1.DataSource = ds;


Saturday, 5 May 2012

Arrays in C#

Arrays -- Store homogeneous data types. memory is allocated in continuous memory blocks
C# supports , single, multiple, jagged arrays.

Arrays can contain all value types & all reference types.
Value types are default initialized .(for ex: int & enum with 0 etc.,)
Reference types default initialized with null.

Single array:
         int[] arr = {1,2,3};  //single dimension array with 3 elements indexed with 0,initialized with values 1,2,3 .
          int[] arr2=new int[3]; //another syntax array with 3 elements indexed with 0, initialized with default value 0 for all elements.

Multiple Arrays

       int [,] marray=new int[2,2];

all elements in this array initialized with int default values . i.e 0.

for(int  i=0; i < i < marray.Get(0);i++)
    for(int j=0; j < marray.Get(1);j++)
            marray[i,j]= i+(j*10);

Jagged Arrays
  Arrays of Arrays. Each Arrays elements point to an Array.
int [][] jarray = new int[2][2];
It has 2 elements each one point to another Single dimensional array.

syntax 2
int[][,] jarray2 = new int [3][,]
jarray2 has elements each one point to one multi-dimensional array.

C# Introduction

C#(C-Sharp) is one of the programming language supported by .NET framework,.  It's complete object-oriented, type safe programming language. It follows same syntax as C,C++,java.
Garbage Collection(GC), which will automatically reclaim unused object's memory This is similar to  Java, Visual Basic etc.,

C# has unified type systems, Where all data types(primitive, user defined) types  derived from single root Object class.

C# doesn't support multiple inheritance.
C# Programs are packaged as Assembly. Which has name ,optionally version,culture, and public key token.