Monday, December 10, 2012

8 WAYS OF CREATING INSTANCE


1. Simple with new keyword
Example1-:
public class Person
{
    public string Name;

}
Person P = new Person();
           P.Name="Deepak";

Example3-: Interface having reference of class
class Program
    {
        
       static void Main(string[] args)
        {
            IHuman P = new Person();
            P.getName();
        }
 

    }

interface IHuman
{
    void getName();
}

public class Person :IHuman
{
  
   public void getName()
   {
       Console.WriteLine("Deepak");
       Console.ReadKey();
   }

}

Example3-: Base Class having reference of derived class.
class Program
    {
        
       static void Main(string[] args)
        {
            DAD D;
            D=new Son1();
            D.getName();
            D = new Son2();
            D.getName();
            Console.ReadKey();
        }
 

    }

 public class DAD
 {
     public virtual void  getName()
     {
         Console.WriteLine("FATHER");
        
     }

 }
public class Son1 :DAD
{
  
   public override void getName()
   {
       Console.WriteLine("SON1");
      
   }

}
public class Son2:DAD
{

    public override void getName()
    {
        Console.WriteLine("SON2");
       
    }

}



2. Activator Class-:
Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited. 


Example1-:
using System;
using System.Reflection;
using System.Text;

public class SomeType
{
    public void DoSomething(int x)
    {
        Console.WriteLine("100 / {0} = {1}", x, 100 / x);
    }
}

public class Example
{
    static void Main()
    {
        // Create an instance of the StringBuilder type using  
        // Activator.CreateInstance.
        Object o = Activator.CreateInstance(typeof(StringBuilder));

        // Append a string into the StringBuilder object and display the  
        // StringBuilder.
        StringBuilder sb = (StringBuilder) o;
        sb.Append("Hello, there.");
        Console.WriteLine(sb);

        // Create an instance of the SomeType class that is defined in this  
        // assembly.
        System.Runtime.Remoting.ObjectHandle oh =
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase,
                                         typeof(SomeType).FullName);

        // Call an instance method defined by the SomeType type using this object.
        SomeType st = (SomeType) oh.Unwrap();

        st.DoSomething(5);
    }
}




Example2-:
    Type T = System.Web.Compilation.BuildManager.GetCompiledType
                         ("//DynamicCompilation//Default2.aspx");
    object obj=  Activator.CreateInstance(T);
    MethodInfo m = T.GetMethod("function");
    object ret=m.Invoke(obj, null);
    Response.Write(ret.ToString());

3. Using assembly class -:Assembly.CreateInstance

Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.
Example-:
 System.Reflection.Assembly ptr =
System.Reflection.Assembly.LoadFrom("ClassLibrary1.dll");
  // get type of class test from just loaded assembly
  Type calcType = ptr.GetType("MyClass2");
    //get the method from above type
     MethodInfo m = calcType.GetMethod("AddNumb");
      //create instance of cass
       object calcInstance = ptr.CreateInstance("MyClass2");
     //invoke the method
    object str=m.Invoke(calcInstance,null);
       MessageBox.Show(str.ToString())

4. Object.MemberwiseClone Method

The MemberwiseClone method creates a shallow copy by creating a new objectand then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
Example-:
    class Program
    {
        static void Main(string[] args)
        {

            Person P = new Person();
            P.Name = "Deepak";
            Person D = P.CreateDuplicateInsatnce();
            Console.WriteLine(D.Name);
         
        }

    }

public class Person
{
   
    public string Name;
   

    public Person CreateDuplicateInsatnce()
    {
       return (Person)this.MemberwiseClone();
    }

}


 

5. Serialize and Deserialize

In simple words, we can say an object conversion in text stream is serialization and text stream creation in object of a classis called deserialization
Example-:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

    class Program
    {
        
       static void Main(string[] args)
        {
            Serialize();
            Deserialize();
        }
        static void Serialize()
        {
           Person P = new Person();
           P.Name="Deepak";
           FileStream fs = new FileStream("DataFile.dat"FileMode.Create);
           BinaryFormatter formatter = new BinaryFormatter();
           formatter.Serialize(fs, P);
           fs.Close();


        }
        static void Deserialize()
        {
            Person D = null;
            FileStream fs = new FileStream("DataFile.dat"FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();
            D = (Person)formatter.Deserialize(fs);
            fs.Close();
            Console.WriteLine(D.Name);
            Console.ReadKey();

        }

    }

 [Serializable]
public class Person
{
    public string Name;
    public Person CreateDuplicateInsatnce()
    {
       return (Person)this.MemberwiseClone();
    }

}

6. Server.CreateObject(ASP WAY)-:


The CreateObject method creates an instance of an object. 
Example-:
<%
Set adrot=Server.CreateObject("MSWC.AdRotator")
%>


7.  ChannelFactory(WCF Way)-:

Using the ChannelFactory<T> class to make calls to your WCF services is an easier alternative to the laborious process of generating proxies via the SvcUtil tool every time a service contract changes. As its name suggests, ChannelFactory is a factory for creating service communication channels at runtime and creates object .

Example-:

 

[ServiceContract]public interface IService1{
    [OperationContract]
    
string GetData(int value);
    [OperationContract]
    
CompositeType GetDataUsingDataContract(CompositeType composite);
    // TODO: Add your service operations here}
BasicHttpBinding myBinding = new BasicHttpBinding();EndpointAddress myEndpoint = new EndpointAddress("http://localhost:3047/Service1.svc");ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>(myBinding, myEndpoint);
IService1 instance = myChannelFactory.CreateChannel();
// Call Service with new object
Console.WriteLine(instance.GetData(10));
myChannelFactory.Close();
 8AppDomain.CreateInstanceAndUnwrap

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.
Example-:

using System;
using System.Reflection;

public class Worker : MarshalByRefObject
{
    public void PrintDomain() 
    { 
        Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName); 
    }
}

class Example
{
    public static void Main()
    {
        // Create an ordinary instance in the current AppDomain
        Worker localWorker = new Worker();
        localWorker.PrintDomain();

        // Create a new application domain, create an instance 
        // of Worker in the application domain, and execute code 
        // there.
        AppDomain ad = AppDomain.CreateDomain("New domain");
        Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(
            Assembly.GetExecutingAssembly().FullName,
            "Worker");
        remoteWorker.PrintDomain();
    }
}

No comments:

Post a Comment