Thursday, September 4, 2008

using System;
using System.Collections.Generic;
using System.Text;
using wr = System.Console;


namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Console.WriteLine(args[0]);
            //this.nonstatic(); //no non static methods are accessable.
            //nstring();
            //extra();
            //stconstr();
            // nstuct();
            ////mypass.run();
            //myparam.run();
            //myprop3.Run();
            //myindex.run();
            //attclass.run();
           // intclass2.run();
            //Pr1.run();
            wr.ReadLine();
        }


        public static void temp()
        { }
        //private variables that are not marked as static cannot be utilised by a static method. 
        public void nonstatic() { } //It is invalid for one static method to directly 
        //call a non-static method or property without first instantiating an object.  


        public static void nmystatic1()
        {
            new mystatic1();
            new mystatic1();
            wr.WriteLine(mystatic1.varstat1);

        }
        public static void stconstr()
        {
            mystatic2 ms = new mystatic2();
            wr.WriteLine("hostname : {0} and ipaddres : {1}", mystatic2.hostname, mystatic2.ipaddr);
        }
        public static void nstring()
        {
            Emp e = new CEmp();
            CEmp x = (CEmp)e;   //write usage 
            // x = (CEmp) new Emp();   //wrong usage
            //    x.Cstring();

        }
        public static void extra()
        {
            Emp e = new Emp();
            wr.WriteLine(e.GetType());
            wr.WriteLine(e.GetHashCode());
            wr.WriteLine(e.ToString());

        }
        public static void nstuct()
        {
            mystruct1 st1;
            st1.e = 1;
            st1.r = 2;
            st1.w = 3;
            mystruct1 st2 = new mystruct1(); //it will initialize all the int types with 0
            Console.WriteLine("{0} {1}", st2.e, st1);


        }
    }

}
class Emp : System.Object
{
    public Emp() { }

}
class CEmp : Emp
{
    public CEmp()
    { Cstring(); }
    public void Cstring()
    {

        string[] str = { "sfsf", "sdf", "sdfsf" };
        //string[] str2 = { "sfsf", 2, 3};
        string[] str1 = new string[1];
        int[] arr1;
        arr1 = new int[10];
        arr1 = new int[20];
        wr.WriteLine(arr1[5]);
        int[,] arr2;
        arr2 = new int[2, 3]; //Multidimensional arrays:
        wr.WriteLine(arr2[0, 1]);
        int[][] arr3; //Array-of-arrays (jagged)
        arr3 = new int[4][];
        for (int i = 0; i <>
            arr3[i] = new int[i + 1];
        string str3 = @"c:\Docs\Source\a.txt";         //@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"
        wr.WriteLine(str3 + "      " + str3[2]);
        str3 = @"sdfsfsf";
        str1[0] = "hello";
        Console.WriteLine(str1[0]);
        // Console.ReadLine();
        //@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"

        //ConsoleApplication1.Program.Main(str1); //correct


    }



}

// private class mystatic  { } // no access mofifiers in class



class mystatic1
{
    public mystatic1()
    { varstat1++; }
    public static int varstat1;
}
class mystatic2
{
    /*//A static constructor is used to initialise the static state of a class when 
    //it is first used.  access modifiers private or publiv arent allowed on static 
     * constructors..  A static constructor therefore has no facility to add parameters.
     * It is also not possible to include a static destructor.
    //static constructors are used to initialize static fields, readonly or otherwise.
    //we are not writing any access modifier for static constructor as they are by definition, always public.
     * you can have only one static constructor and it cant access instance members including this pointer.
     * you can provide a non static constructor with the same signature as static constructor and if u 
     * do this then both constructors will get called before the first instance of a class
     * is created with the static version called first.
     */
    static mystatic2()
    {
        System.Net.IPAddress ipad = System.Net.Dns.Resolve(hostname).AddressList[0];
        ipaddr = ipad.ToString();
    }
    public const string hostname = @"www.google.com";
    public static readonly string ipaddr;

}

sealed class mysealed
{
    public mysealed(int x, int y)
    {
        this.x = x;
        this.y = y;

    }

    int x, y;
}

/*like a class, a stuct dont incur the overhead associated with reference objects.
client doesnt have to instantiate the stuct(new keyword). its a value type so is allocated
 once its declared.
 */
public struct mystruct1 //doesnt have a default constructor
{
    public int r, w, e;
    public override string ToString()
    {
        return w.ToString();
    }
}
/* u sue struct when data is very small or it contais few or no methods to access or modify
 * constained data
 * a class is an encapsulation of data and the methods that work on that data. structs can
 * be viewed as simple data.
 */
public struct mystruct2
{
    //public mystruct2() //parameterless constructor of a structure is not allowed.
    public mystruct2(int r, int w, int e)
    {
        this.e = e;
        this.w = w;
        this.r = r;

    }
    public int r, w, e;
}
//passing reference type by reference is same as passing by value.
class mypass
{
    public mypass()
    {
        a = 10;
        b = 20;
        c = 30;
    }

    int a;
    int b;
    int c;
    public void valpass(int a, int b, int c)
    {
        a = 5;
        b = 10;
        c = 15;
        wr.WriteLine("val pass : {0} {1} {2}", a, b, c);
    }
    public void refpass(ref int a, ref int b, ref int c)
    {
        a = this.a;
        b = this.b;
        c = this.c;
        wr.WriteLine("ref pass : {0} {1} {2}", a, b, c);
    }
    public void outpass(out int a, out int b, out int c) //out parameters must be modified in the called method.
    {
        // c = a; can not use out parameter before modifying
        a = this.a + 1;
        b = this.b + 1;
        c = this.c + 1;
        wr.WriteLine("out pass : {0} {1} {2}", a, b, c);
    }

    public void objpass(out mypass m)
    {
        // int x = m.a; can not use m before assigning it to another object
        m = new mypass(); //now u can use it.

    }
    //passing reference type by reference is same as passing by value.
    public void objpass2(ref mypass m1, mypass m2)
    {
        //will work same 
        m1.a = m1.a + 1;
        m2.a = m2.a + 1;
        //will work diff
        m1 = new mypass(); //same ref is passed so value will get changed in the root ref
        m2 = new mypass(); //copy of the reference is passed so root will remain unchanged.
    }
    public static void run()
    {
        int a = 1, b = 2, c = 5; // for ref and val parameter initialization is necessary
        int d = 1, e = 2, f = 5;
        int g = 6, h, i;        // parameter may or may not be initialized for out.
        mypass m = new mypass();
        wr.WriteLine("val pass : {0} {1} {2}", a, b, c);
        m.valpass(a, b, c);
        wr.WriteLine("ref pass : {0} {1} {2}", d, e, f);
        m.refpass(ref d, ref e, ref f);
        //wr.WriteLine("ref pass : {0} {1} {2}", g, h, i);
        m.outpass(out g, out h, out i);
    }

}
/*method overload
 * access modifier and return type doesnt count
 * ref and out are enough
 * you can use either ref or out but not both,
 constructor overloading -
 * its like public func_constructor(int a) : this()
 * where this is default constructor but no longer valid after the explicit use.
 * we can also call other constructor from one constructor like this
 * public func_constructor(int a) : this("hello")
 * overloaded methos is considered an overloaded even if other overloaded versions of the
 * funcitons exist in the base class rather than current class.
 */
class myparam
{
    static void param1(params int[] a)
    {
        foreach (int b in a)
        {
            wr.WriteLine(b);
        }
        //or
        /*  for (int i = 0; i <>
          {
              wr.WriteLine(a[i]);
          }*/
        /* public void func(params object[] a)
         * it can take ny number of parameters of ny type
         */
    }
    public static void run()
    {
        param1(1, 2);
        param1(5, 6, 7);
    }
}

/*method overriding - type of polymorphism
 *in the derived method, wherther we are using 'new' of not, it will be by default to all 
 * the methods with diff name diff arguments or same name same arguments.
 * in the upcast the base reference will always point to the base method.
 * it happpens due to early binding which is binding of method at compile time which is
 * C# looks at the call and determines the address in memory needed to jump to when call
 * is made and in case memory location of the method.
 * late binding means that the compiler doesnt select the method to excute until runtme.
 * for this we must use virtual and override keyword.
 * polymorphic class - using virtual and override
 * non polymorphic class - using new.
 * the point is in virtual function table
 * a constructor cant be virtual.
 * new virtual is also possible - only virtual means new by default.
*/

class myprop1
{
    int salary = -1;
    public virtual int Salary
    {
        // get; allowed only for abstract or extern class
        get
        { return salary; }
        set { }
    }
}
/* only getter - readonly property..only setter - write only property
 * both setter n getter - read-write property
 * cant be used as parameter to methods.
 * static properties doesnt not have virtual abstract or override keywords
 * members defined as abstract within an abstract class must be implemented by any derived class
 * 
*/
class myprop2 : myprop1
{
    int salary = 10;
    public override int Salary
    {
        get
        {
            return salary + 5;
        }

        set
        {
            salary = value;
        }
    }
}
class myprop3 : myprop1
{
    int salary = 20;
    public override int Salary
    {
        get
        {
            return salary + 1;
        }
        set
        {
            salary = value;
        }


    }

    public static void Run()
    {
        myprop1[] m1 = new myprop1[2];
        m1[0] = new myprop2();
        m1[1] = new myprop3();
        wr.WriteLine("1st {0} 2nd {1}", m1[0].Salary, m1[1].Salary);
        m1[0].Salary = 50;
        m1[1].Salary = 100;
        wr.WriteLine("1st {0} 2nd {1}", m1[0].Salary, m1[1].Salary);

    }
}

class myindex
{
    System.Collections.ArrayList a = new System.Collections.ArrayList();
    public object this[int i]
    {
        get
        {
            if (i > -1 && i <>
                return a[i];
            else
                return "error";

        }
        set
        {
            if (i <>
                a[i] = value;
            else if (i == a.Count)
                a.Add(value);
        }
    }
    public static void run()
    {
        myindex m = new myindex();
        m[0] = "asfd";
        m[1] = 2;
        wr.WriteLine(m[0] + "  " + m[1]);
        wr.WriteLine(typeof(myindex));
        //wr.WriteLine(m[0],m[1]);   //error

    }



}

public enum myenum
{
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
class myattribAttribute : Attribute
{
    public myattribAttribute(string name)
    {
        this.Name = name;
    }

    myenum day;
    public myenum Day
    {
        get { return day; }
        set { day = value; }
    }
    string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

}

[myattrib("DayThursday", Day = myenum.thursday)]
class attclass
{
    [myattrib("DayWednesday", Day = myenum.wednesday)]
    public void Method()
    {
    }
    public void method2() { }
    [myattrib("DayFiday", Day = myenum.friday)]
    public int field;
    public int field1;
    public static void run()
    {
        Type type = Type.GetType("attclass");
        foreach (Attribute att in type.GetCustomAttributes(true))
        {
            if (att is myattribAttribute)
            {
                myattribAttribute myat = att as myattribAttribute;
                wr.WriteLine("{0} {1}", myat.Name, myat.Day);
            }
        }
        foreach (System.Reflection.MemberInfo mi in type.GetMethods())
        {
            foreach (Attribute att in mi.GetCustomAttributes(true))
                if (att is myattribAttribute)
                    wr.WriteLine(mi.Name);
                else wr.WriteLine("not {0}", mi.Name);
        }
        foreach (System.Reflection.FieldInfo fi in type.GetFields())
        {
            foreach (Attribute att in fi.GetCustomAttributes(true))
            {
                if (att is myattribAttribute)
                {
                    myattribAttribute myat = att as myattribAttribute;
                    wr.WriteLine(fi.Name);
                    wr.WriteLine("{0} {1}", myat.Name, myat.Day);
                }
            }
        }
    }

}
class intclass1
{
    void printf1()
    {
        wr.WriteLine("print int class1");
    }
}
interface inf1
{
    int count();
    void printf1();
}
interface inf2
{
    void printf2();
}
interface inf3 : inf1, inf2
{ }
interface inf4
{
    int count();
}
class intclass2 : intclass1, inf3, inf4
{
    public void printf2()
    {
        wr.WriteLine("intf3->intf2");
    }
    public void printf1() //new keyword is by default
    {
        wr.WriteLine("intf3->intf1");

    }

    int inf1.count() //inf1 is used instead inf3
    {
        return 2;
    }
    int inf4.count()
    {
        return 3;
    }
    public static void run()
    {
        intclass2 infc2 = new intclass2();
        ((inf3)infc2).printf1();
        // infc2.count-----name hidding

    }

}

class myclock
{
    public delegate void del(Timeargs t1);
    public event del ev;
    int sec, hour, min;
    public void onsecchange(Timeargs ti)
    {
        if (ev != null)
            ev(ti);
    }
    public void run()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(1000);
            DateTime dt = DateTime.Now;
            if (dt.Second != sec)
            {
                Timeargs tm = new Timeargs(dt.Hour, dt.Minute, dt.Second);
                this.sec = dt.Second;
                this.hour = dt.Hour;
                this.min = dt.Minute;
                onsecchange(tm);
            }

        }

    }

}
class logi
{
    public void subscribe(myclock mc)
    {
        mc.ev += new myclock.del(logger);
    }
    public void logger(Timeargs tm)
    {
        Console.Write("\r{2}:{0}:{1}", tm.min, tm.sec, tm.hour);
    }
}
class Timeargs
{
    public Timeargs(int hour, int min, int sec)
    {
        this.hour = hour;
        this.sec = sec;
        this.min = min;
    }
    public readonly int hour, min, sec;
}

class Pr1
{

    
    public static void run()
    {
        string[] a = new string[5];
        myclock mc = new myclock();
        logi lg = new logi();
        lg.subscribe(mc);
        mc.run();
       // Console.ReadLine();




    }
    private static void func1(string message)
    {
        Console.WriteLine(message);

    }
}

C#.Net vs VB.Net

n Visual C# you can document the code you write using XML. C# is the only programming language in Visual Studio .NET with this feature.

.net C#.net and VB.net

ACCESS MODIFIERS
 * Classes and structs that are declared directly within a namespace (in other words, they are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
 * Nested classes and structs may also be declared as private. Private nested types are not accessible from the containing type.

Derived classes cannot have greater accessibility than their base types. In other words, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
Class members (including nested classes and structs) can be declared with any of the five types of access. Struct
 * members cannot be declared as protected because structs do not support inheritance.

The accessibility of a member can never be greater than the accessibility of its containing type. For example, 
 * a public method declared in an internal type has only internal accessibility.

When a member of a class or struct is a property, field, method, event, or delegate, and that member either is a 
 * type or has a type as a parameter or return value, the accessibility of the member cannot be greater than the 
 * type. For example, you cannot have a public method M that returns a class C unless C is also public. Likewise,
 * you cannot have a protected property of type A if A is declared as private.

User-defined operators must always be declared as public

Interfaces declared directly with a namespace can be declared as public or internal and like classes and structs,
 * interfaces default to internal access. Interface members are always public because the purpose of an interface 
 * is to enable other types to access a class or struct. No access modifiers can be applied to interface members.

Enumeration members are always public, and no access modifiers can be applied.

By default, delegates have internal access.

Any types declared within a namespace or at the top level of a compilation unit (for example, not within 
 * a namespace, class, or struct) are internal by default, but can be made public.
*/

/*
A private constructor is a special instance constructor. It is commonly used in classes that contain static members 
 * only. If a class has one or more private constructors and no public constructors, then other classes
 * (except nested classes) are not allowed to create instances of this class.
 * if you are designing your own type that contains only static members then you should mark the type as Sealed 
 * and define a private parameterless contructor that is never called.
*/

/*
C# doesnt allow a value type to define a parameterless constructor.
 * keep in mind that although C# doesnt allow value types with pareameterless costructors, the CLR does.
 * 
 *     struct point
    {
                public int x=5,y; // cannot have instance field initializers in structs. so x=5 is wrong..
 *                               //becoz there are no default constructors. so int x is correct but int x=5 is wrong...
                public classA a; //an object can be a part of a value type
 * 
 *                public point() // wrong...parameterless constructor is not allowed
 *              public point(int x)
 *              {
 *                  //in a constructor u have to initialize each field else compilation error
 *              this.x=x;
 *              this.y=x;
 *              this.a=new classA();
 *              }
 * }
 * 
 * system.int32 a = new system.int32() and int a = 0 has same code in IL. that mean when we wrote 0 then implicit constructor was called.
 * Any data type that compliler directly supports are called primitive types.   
we do not have instance field initializers in structs....so no objects in value types can be instantiated
*/

/* 
 *a new operator has no complementary delete oerator that is there is no way to explicitly free the memory allocated for an object. 
 * MSCorLib.dll assembly contains the definitions of all the core .NET Framework class Library types, such as Object, int32, String and so on.
 * all the value types of class are allocated in the heap and not on stack, only the value types of the functions are allocated on stack
 * in c#, types declared using struct are value types adn types declared using class are refernce types. 
 * Value types are derived from system.valuetype which is again derived from system.object.system.valuetype overrides
 * the equal method so that it returns true if the values fo the two object's fields match.
 * it also overrides the gethashcode method so that it produces a hash code value using an algorithm that takes into 
 * account the values in the objects instance fields.
 * the reason why a type must define both equals and gethashcode is that the implementation of the 
 * system.collections.hashtable type requires that any two objects that are equal must have same hash code value. 
 * 
 * 
 * someval v1; //someval is a value type.
 * this line produces IL that allocates the instance on the thread stack and zeroes the fields.the only problem is 
 * that C# thinks the instance initialized if u use the new operator or a direct value. so if u try to use it will
 * throw complile time error.
 * 
 * 
 *A READONLY variable can only be assigned in a constructor or variable initializer(repeations are allowed) but
 * cant be declared in a function or constructor.
 * 
 * The compiler saves the CONSTANT value in the module metadata. You can define constant only for types that your
 * compiler considers as primitive types.
 * 
 * A lot of types(System.String) overload the equality (==) and inequality operators.
 * 
 * 
 * An EVENT in C# is a way for a class to provide notifications to clients of that class when some interesting
 * thing happens to an object.
 * DELEGATE is a class that derive from System.MulticastDelegate and includes following  members:
 * EnumConnectionCallback constructor
 * Invoke
 * BeginInvoke
 * EndInvoke
 * 
 * 
 * XML DUCUMENTATION - One of the nice side-effects of setting this configuration value is that documentation 
 * warnings are then enabled:
All overlaoded OPERATOR methods must be defined as public and static.
* should have a return type
* unary operator - single argument, binary operator - 2 arguments.
*
* DELEGATES are reference types that encapsulate a method(either static or instance) with a specified signature.
* CALLBACK methods enable you to pass a function pointer to another function that will then call you back.