What is the best way for declaring static fields

Today I wrote a simple application, which shows what the difference is between initializing a static field in the explicit static constructor and doing the same during the declaration time (inline). I know that even when we initialize our static fields inline, the compiler will add an implicit static constructor to that class and initialize static values in that method. But this example showed me that there is really a long time difference between initializing static fields inline and in explicit static constructor. Here are a screenshot from the example - in this example BeforeFieldInit means that the static fields are initialized inline and NotBeforeFieldInit means that static fields are initialized in the explicit static constructor:

Screen Capturing Example

Download Example Code

Declaring a static field and initializing its value in an explicit static constructor.

using System;

namespace
BeforeFieldInitExample
{
    public class
NotBeforeFieldInit
    {
        // here there is only decleration of the static field
        public static int
A;

        static
NotBeforeFieldInit()
        {
            // Initialization of A's values is here in the explicit static constructor
            A = 0;
        }
    }
}


Initializing a static fields value during the decleration (inline).

using System;

namespace
BeforeFieldInitExample
{
    public class
BeforeFieldInit
    {
        public static int
A = 0;
    }
}


These two code groups will work as the same and produce the same result. Actually when we compile the second code, the output will be as the same with the first code. I mean, during the compiling time the compiler will create an implicit static constructor for the BeforeFieldInit class and initialize the field's value in that method. So it will be the same with the first code.

But there is a small difference between these codes. The difference can only be seen by checking the IL codes of these types.

For the first example, IL code of the class NotBeforeFieldInit will be as follows:

.class public auto ansi NotBeforeFieldInitClass
            extends
object
{
    .
method public hidebysig specialname
            rtspecialname instance
            void .ctor() cil managed
    {
        // Code Size: 7 byte(s)
        .maxstack
8
        L_0000: ldarg.0
        L_0001: call instance
void object::.ctor()
        L_0006: ret
    }

    .
method private hidebysig specialname
            rtspecialname static
            void .cctor() cil managed
    {
        // Code Size: 22 byte(s)
        .maxstack
8
        L_0000: nop
        L_0001: ldc.i4.0
        L_0002: stsfld int32 BeforeFieldInitExample.NotBeforeFieldInitClass::A
        L_0007: ldc.r8 9
        L_0010: stsfld float64 BeforeFieldInitExample.NotBeforeFieldInitClass::B
        L_0015: ret
    }

    .field public static
int32 A
    .
field public static
float64 B
}


And for the second example, which the name of the class is BeforeFieldInit's IL code will be as runs:
.class public auto ansi
            beforefieldinit // here beforefieldinit mask is added
                BeforeFieldInitClass

        extends object
{
    .
method public hidebysig specialname
            rtspecialname instance
            void .ctor() cil managed
    {
       // Code Size: 7 byte(s)
        .maxstack
8
        L_0000: ldarg.0
        L_0001: call instance
void object::.ctor()
        L_0006: ret

    }

    .method private hidebysig specialname
            rtspecialname static
            void .cctor() cil managed
    {
        // Code Size: 21 byte(s)
        .maxstack
8
        L_0000: ldc.i4.0
        L_0001: stsfld int32 BeforeFieldInitExample.BeforeFieldInitClass::A
        L_0006: ldc.r8 9
        L_000f: stsfld float64 BeforeFieldInitExample.BeforeFieldInitClass::B
        L_0014: ret

     }

    .field public static int32 A
    .
field public static
float64 B
}

IL codes generated by Xenocode Fox 2007

As you see in the IL the only difference between these two codes is the second class's having the beforefieldinit flag. So what is this flag doing?

beforefieldinit flag tells to the JIT that this class's static fields are initialized inline. If a class has no beforefieldinit flag, then JIT compiler will automatically check whether explicit static constructor is called before. This means that whenever you want to try to access any static member of this class or try to create a new instance of this class, JIT will automatically calls the explicit static constructor. Therefore you will loose performance because whenever you try to access a static member, JIT also checks whether static constructor is invoked before. But in the second example if we add a beforefieldinit flag to our class, this means that our static members are initialized inline, so JIT does not need to check whether static constructor is invoked before. This is the main reason that causes performance difference between those two classes. When we wrote an explicit static constructor and initialize our fields' values, the compiler will not add beforefieldinit flag to that class. But if we initialize our static fields inline, then compiler will add an implicit static constructor and initialize our static fields there and also add the beforefieldinit flag to our class.

So always, try to use inline field initialization for the static fields if you can.

Capturing Screenshot and Paste Any Image to the Screen

Screen Capturing ExampleFor a very long time ago (about 4 years...), in one of my projects, I needed to capture the screenshot which must have to support both full screen capturing and specific regional capturing.

Also I need to paste that captured image back to the screen programmatically. At that moment I solved my problem by using some WinApi methods in the user32.dll and gdi32.dll. Here I want to share that code with you. You can also download the example source codes.

To use this code;
Use CaptureScreen() method to capture whole screen;
Use CatureRegion(Region) to capture only the given region of the screen;
Use PasteToScreen(Bitmap, Region) method to paste any image to the given region on to the screen.

Download Source Codes and Demo Exe 

Here are the codes ...

public class NativeMethods
{
    ///
<summary>
   
///
Takes a screenshot of full screen
   
///
</summary>
   
/// <returns>Return the Bitmap of the Screen
</returns>
   
public static Bitmap
CaptureScreen()
    {
        return CaptureRegion(null
);
    }

    /// <summary>
    ///
Takes a Screen Shot of the given rectangle.
    ///
</summary>
    /// <param name="rct">Rectangle area which we try to get the screen shot.
</param>
    /// <returns>Return the Bitmap of the screen defined rectangle.
</returns>
    public static Bitmap CaptureRegion(Rectangle
rct)
    {
        return CaptureRegion(new Region
(rct));
    }

    /// <summary>
    ///
Takes a screen shot of the given region.
    ///
</summary>
    /// <param name="rgn">Region that which we try to get the picture of it.
</param>
    /// <returns>
Returns the Bitmap of the given region.
    ///
Bitmap Size will be equal to the GetBounds() of the Region.
    ///
Any other points that they are not in the region and
    /// which are in the Bounds will be as Color.Transparent.
</returns>
    public static Bitmap CaptureRegion(Region
rgn)
    {
        IntPtr
hSDc, hMDc;
        IntPtr
hBtm, hOldBtm;
        Size imgSize = Size
.Empty;
        int
xCoor = 0, yCoor = 0;
        if (rgn == null
)
        {
            hSDc = CreateDC("DISPLAY", string.Empty,string.Empty, string
.Empty);
            hMDc = CreateCompatibleDC(hSDc);
            imgSize = new Size
(GetDeviceCaps(hSDc, 8),
            GetDeviceCaps(hSDc, 10));

            GraphicsPath p = new GraphicsPath
();
            p.AddRectangle(new Rectangle
(0, 0, imgSize.Width, imgSize.Height));
            rgn = new Region
(p);
        }
        else
        {
            hSDc = GetDC(IntPtr
.Zero);
            SelectClipRgn(hSDc, rgn.GetHrgn(Graphics
.FromHdc(hSDc)));
            hMDc = CreateCompatibleDC(hSDc);

            RECT myBox = new RECT();
            GetClipBox(hSDc, ref
myBox);
            imgSize = new Size
(myBox.Width, myBox.Height);
            xCoor = myBox.left;
            yCoor = myBox.top;
        }

        hBtm = CreateCompatibleBitmap(hSDc,
                imgSize.Width, imgSize.Height);
        hOldBtm = SelectObject(hMDc, hBtm);
        BitBlt(hMDc, 0, 0, imgSize.Width, imgSize.Height,
                hSDc, xCoor, yCoor, RasterOperations
.SRCCOPY);
        hBtm = SelectObject(hMDc, hOldBtm);

        DeleteDC(hSDc);
        DeleteDC(hMDc);

        Bitmap bmp = Bitmap.FromHbitmap(hBtm);
        RectangleF rct = rgn.GetBounds(Graphics
.FromImage(bmp));
        RectangleF[] rcts = rgn.GetRegionScans(new Matrix
());
        for (int
i = 0; i < rcts.Length; i++)
        {
            rcts[i].X -= rct.X;
            rcts[i].Y -= rct.Y;
        }

        for (int x = 0; x < bmp.Width; x++)
        {
            for (int
y = 0; y < bmp.Height; y++)
            {
                bool isIn = IsInRectangles(rcts, (float)x, (float
)y);
                if
(!isIn)
                    bmp.SetPixel(x, y, Color
.Transparent);
            }
        }
        DeleteObject(hBtm);
        return
bmp;
    }

    /// <summary>
    ///
Checks that is in region.
    ///
</summary>
    public static bool IsInRegion(Region rgn, Point
pt)
    {
        RectangleF[] rcts = rgn.GetRegionScans(new Matrix
());
        return
IsInRectangles(rcts, pt);
    }

    public static bool IsInRectangles(RectangleF[] rcts, Point
pt)
    {
       return IsInRectangles(rcts, (float)pt.X, (float
)pt.Y);
    }

    /// <summary>
    ///
 Checks that is Point in Rectangles (Scans of Region).
    ///
</summary>
    public static bool IsInRectangles(RectangleF[] rcts, float x, float
y)
    {
        for (int
i = 0; i < rcts.Length; i++)
        {
            if
(rcts[i].Contains(x, y))
            {
                return true
;
            }
        }
        return false
;
    }

    public unsafe static void PasteToScreen(Bitmap bmp, Region rgn)
    {
        if (bmp == null || rgn == null
)
            return
;
        IntPtr hDc = GetDC(IntPtr
.Zero);
        Graphics g = Graphics
.FromHdc(hDc);
        RectangleF rctF = rgn.GetBounds(Graphics
.FromHdc(hDc));
        Rectangle rct = new Rectangle((int)rctF.X, (int)rctF.Y,
                                   (int)rctF.Width, (int
)rctF.Height);
        g.SetClip(rgn, CombineMode
.Replace);
        g.DrawImage((Image
)bmp, rct);
        DeleteDC(hDc);
        g.Dispose();
    }

    // NATIVE METHODS
    [DllImport("gdi32.dll"
)]
    public static extern int BitBlt(IntPtr srchDC, int srcX, int
srcY,
                        int srcW, int srcH, IntPtr desthDC, int destX,
                        int destY, RasterOperations
op);

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern IntPtr CreateDC(string lpDriverName,
                        string
lpDeviceName,
                        string lpOutput, string
lpInitData);

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern IntPtr CreateCompatibleDC(IntPtr
hDC);

    [DllImport("gdi32.dll"
)]
    public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetDC(IntPtr
hWnd);

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern int GetClipBox(IntPtr hDC, ref RECT rectBox);    

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern int SelectClipRgn(IntPtr hDC, IntPtr
hRgn);

    [
DllImport("gdi32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,
                                           int nWidth, int nHeight);

    [DllImport("gdi32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SelectObject(IntPtr hDC, IntPtr
hObject);

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern bool DeleteDC(IntPtr hDC);

    [DllImport("gdi32.dll", CharSet = CharSet
.Auto)]
    public static extern IntPtr DeleteObject(IntPtr
hObject);

    [
DllImport("user32.dll")]
    public static extern IntPtr SetTimer(IntPtr hWnd, int nIDEvent,
                                    int uElapse, TimerProc
lpTimerFunc);

    public delegate void TimerProc(IntPtr hWnd, int msg, IntPtr wParam,
                                      IntPtr
lParam);

    [DllImport("user32.dll"
)]
    public static extern bool KillTimer(IntPtr hwnd, int idEvent);


    public enum RasterOperations :
uint
    {
        SRCCOPY = 0x00CC0020,
        SRCPAINT = 0x00EE0086,
        SRCAND = 0x008800C6,
        SRCINVERT = 0x00660046,
        SRCERASE = 0x00440328,
        NOTSRCCOPY = 0x00330008,
        NOTSRCERASE = 0x001100A6,
        MERGECOPY = 0x00C000CA,
        MERGEPAINT = 0x00BB0226,
        PATCOPY = 0x00F00021,
        PATPAINT = 0x00FB0A09,
        PATINVERT = 0x005A0049,
        DSTINVERT = 0x00550009,
        BLACKNESS = 0x00000042,
        WHITENESS = 0x00FF0062
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct
RECT
    {
        public int
left;
        public int
top;
        public int
right;
        public int
bottom;

        public
int Width
        {
            get { return
right - left; }
        }

        public int
Height
        {
            get { return
bottom - top; }
        }
    }
}


How to Find SQL Server on a Network

Most of us developing our programs by using MSSQL Server, and it is a necessary for us to make SQL Server selectable in the Options Dialog. But here the problem is how we can find the SQL Servers in the network ?

There are two different way we can use for searching the network for the available Sql Servers.

1 - There is a class in the .NET Framework which name is SqlDataSourceEnumerator in the System.Data.Sql namespace. We can use that class, and get the sql servers easly:

DataTable sqls = SqlDataSourceEnumerator.Instance.GetDataSources();

In this method we can only get the Sql Server machines on a network. But in the second method we can also search the Terminal machines, server machines etc.

2 - We can use NetServerEnum function in the netapi32.dll. The following code demonstrates us how we can find SQL Servers in a network...

public class NativeMethods
{
    public const uint
ERROR_SUCCESS = 0;
    public const uint
ERROR_MORE_DATA = 234;
    

   
[
DllImport("netapi32.dll", EntryPoint = "NetServerEnum"
)]
    public static extern int
NetServerEnum(
            [MarshalAs(UnmanagedType
.LPWStr)]
            string
servername,
            int
level,
            out IntPtr
bufptr,
            int
prefmaxlen,
            ref int
entriesread,
            ref int
totalentries,
            SV_101_TYPES
servertype,
            [MarshalAs(UnmanagedType
.LPWStr)]
            string
domain,
            int resume_handle);
 
    

   
[DllImport("netapi32.dll", EntryPoint = "NetApiBufferFree"
)]
    public static extern int NetApiBufferFree(IntPtr buffer);

    [StructLayout(LayoutKind.Sequential)]
    public struct
SERVER_INFO_101
    {
        [MarshalAs(UnmanagedType
.U4)]
        public PLATFORM_ID
sv101_platform_id;
        [MarshalAs(UnmanagedType
.LPWStr)]
        public string
sv101_name;
        [MarshalAs(UnmanagedType
.U4)]
        public uint
sv101_version_major;
        [MarshalAs(UnmanagedType
.U4)]
        public uint
sv101_version_minor;
        [MarshalAs(UnmanagedType
.U4)]
        public SV_101_TYPES
sv101_type;
        [MarshalAs(UnmanagedType
.LPWStr)]
        public string
sv101_comment;
    }

    public enum SV_101_TYPES :
uint
    {
        SV_TYPE_WORKSTATION = 0x00000001,
        SV_TYPE_SERVER = 0x00000002,
        SV_TYPE_SQLSERVER = 0x00000004,
        SV_TYPE_DOMAIN_CTRL = 0x00000008,
        SV_TYPE_DOMAIN_BAKCTRL = 0x00000010,
        SV_TYPE_TIME_SOURCE = 0x00000020,
        SV_TYPE_AFP = 0x00000040,
        SV_TYPE_NOVELL = 0x00000080,
        SV_TYPE_DOMAIN_MEMBER = 0x00000100,
        SV_TYPE_PRINTQ_SERVER = 0x00000200,
        SV_TYPE_DIALIN_SERVER = 0x00000400,
        SV_TYPE_XENIX_SERVER = 0x00000800,
        SV_TYPE_SERVER_UNIX = 0x00000800,
        SV_TYPE_NT = 0x00001000,
        SV_TYPE_WFW = 0x00002000,
        SV_TYPE_SERVER_MFPN = 0x00004000,
        SV_TYPE_SERVER_NT = 0x00008000,
        SV_TYPE_POTENTIAL_BROWSER = 0x00010000,
        SV_TYPE_BACKUP_BROWSER = 0x00020000,
        SV_TYPE_MASTER_BROWSER = 0x00040000,
        SV_TYPE_DOMAIN_MASTER = 0x00080000,
        SV_TYPE_SERVER_OSF = 0x00100000,
        SV_TYPE_SERVER_VMS = 0x00200000,
        SV_TYPE_WINDOWS = 0x00400000,
        SV_TYPE_DFS = 0x00800000,
        SV_TYPE_CLUSTER_NT = 0x01000000,
        SV_TYPE_TERMINALSERVER = 0x02000000,
        SV_TYPE_CLUSTER_VS_NT = 0x04000000,
        SV_TYPE_DCE = 0x10000000,
        SV_TYPE_ALTERNATE_XPORT = 0x20000000,
        SV_TYPE_LOCAL_LIST_ONLY = 0x40000000,
        SV_TYPE_DOMAIN_ENUM = 0x80000000,
        SV_TYPE_ALL = 0xFFFFFFFF
    }

    public enum PLATFORM_ID :
uint
    {
        PLATFORM_ID_DOS = 300,
        PLATFORM_ID_OS2 = 400,
        PLATFORM_ID_NT = 500,
        PLATFORM_ID_OSF = 600,
        PLATFORM_ID_VMS = 700
    }
}


We can use the following native methods as follows;

public List<string> GetSqlServers()
{
    List<string> servers = new List<string>();
    int
readed = 0;
    int
total = 0;

    do
    {
        IntPtr
buffer;
        NativeMethods.SERVER_INFO_101
server;
        int retVal = NativeMethods.NetServerEnum(null, 101, out
buffer, -1,
                                ref readed, ref
total,
                                NativeMethods.SV_101_TYPES.SV_TYPE_SQLSERVER, null
, 0);

       
if
(retVal == NativeMethods.ERROR_SUCCESS ||
                    retVal == NativeMethods
.ERROR_MORE_DATA ||
                    readed > 0)
        {
            int
handle = buffer.ToInt32();
            for (int
i = 0; i < readed; i++)
            {
                server = (NativeMethods.SERVER_INFO_101)Marshal
.PtrToStructure(
                                    new IntPtr(handle),
                                    typeof(NativeMethods.SERVER_INFO_101
));

                handle += Marshal
.SizeOf(server);
                servers.Add(server.sv101_name);
            }
        }
        NativeMethods
.NetApiBufferFree(buffer);
    }
    while
(readed < total && readed != 0);

    return
servers;
}


In this example if you call the GetSqlServers method, this will return you the list of the SQL Servers on the network.

Not only for the SQL Servers also you can find any other group of computers by using NetServerEnum method. The SV_101_TYPES enumeration identifies the type of the computer, which you can search for. If you use another value of this enum in GetSqlServers method, you will get the computers list of that kind.

For example; if you are searching for Teminal Servers on the network, use SV_TYPE_TERMINALSERVER while calling NetServerEnum method in the GetSqlServers method. This will returns you the Terminal Servers on the network.

New Projects Uploaded

Some new projects uploaded to the server, you can download them from the Downloads page.

Projects:

FEME Racing: A simple car racing game written int.NET.
Keyboard & Mouse Hook: Keyboard and mouse hook components.
MarshalByRef Example: Marshal by ref object example which uses TcpChannel.
Drag Drop Examples: Some drag and drop examples

B MSN

B-MSN Scree ShotTonight i uploaded an example about Server-Client applications to the server. The name of the example is B-MSN which is an instant messaging program like MSN, AOL or Yahoo IM. Some of the specifications of the B-MSN are;

Supports Smileys
Supports personal image
NetServer and NetClient components which you can also use them as standalone
Flashes window when a new message received
Supports RTF text sending
Informs you while the person whom you chat with is writing a message to you
Supports Saving Message Histories
etc.


You can download source codes and binaries from the Downloads page.

Create object instances Faster than Reflection

Object Create Benchmark Test ResultEverybody knows that Reflection is a really very important topic in .NET. So I won't repeat the importance of it, it is an unquestionable subject; besides, I have to admit that it saved my life too many times. 

But like every good thing Reflection has also some disadvantages, too. One of the important disadvantages of the Reflection is performance. 

Actually, if we talk about considering a few reflection operations, there won't be any performance problem because Reflection is not slow. It is just slower than the other ways which make us do the same operations. For example:
// WAY 1 normal instance creation
ArrayList list = new ArrayList();

// WAY 2 Using reflection to create an instance of a type
ArrayList list = (ArrayList)typeof(ArrayList).GetConstructor(Type.EmptyTypes).Invoke(null);

If we call the methods above not too many times at the same time, there won't be any performance problem but there might be a performance problem if we call this reflection example too many times in any iteration as for, while, foreach etc. For example:

Stopwatch watch = new Stopwatch();
Type t = typeof(ArrayList);
ConstructorInfo info = t.GetConstructor(Type.EmptyTypes);

object o = null;
ArrayList list = null;
watch.Start();
for (int i = 0; i < 1000000; i++)
{
    list = new ArrayList();
}
watch.Stop();
Console.WriteLine(string.Format("new : {0} ms", watch.ElapsedMilliseconds));

GC.Collect();

o = null;
watch.Start();
for (int i = 0; i < 1000000; i++)
{
    o = info.Invoke(null);
}
watch.Stop();
Console.WriteLine(string.Format("Reflection : {0} ms", watch.ElapsedMilliseconds));
When you run the code above, the output will be as follows:
new : 23 ms
Reflection : 1131 ms


As you see in the previous example, if you use Reflection to create too many items, it will work very slowly. To we talk about the first method (using new), we can only use it when we know the object's Type during the coding time. Otherwise, we cannot use the new keyword to create an instance of an unknown type. In the world of programming, this is a very common situation because we usually don't know the actual type during the coding, so we have to use Reflection in scenarios like this to create instances of a Type.

There are two different ways to make this code run faster. One of them is using Activator class to create object instances from Types. If we want to use the Activator class in the example above to create an instance of an object, the code will be as runs:
o = null;
watch.Start();
for (int i = 0; i < 1000000; i++)
{
   o = Activator.CreateInstance(t);
}
watch.Stop();
Console.WriteLine(string.Format("Activator : {0} ms", watch.ElapsedMilliseconds));

If we execute this code, we'll get the following result:

Activator : 207 ms.

However, this is not the best way. Yes, this is fast but there is also another way which run faster than the Activator class.
The last method I mention is using DynamicMethod method. Dynamic method is a method which we instantiate in the runtime in memory, and works as any method we wrote in our programs

/// <summary>
///
Class which creates a dynamic method for the given type
///
</summary>
public class
ObjectCreateMethod
{
    delegate object MethodInvoker
();
    MethodInvoker methodHandler = null
;

    public
ObjectCreateMethod(Type type)
    {
        CreateMethod(type.GetConstructor(Type
.EmptyTypes));
    }

    public
ObjectCreateMethod(ConstructorInfo target)
    {
        CreateMethod(target);
    }

    void
CreateMethod(ConstructorInfo target)
    {
        DynamicMethod dynamic = new DynamicMethod(string
.Empty,
                    typeof(object
),
                    new Type
[0],
                    target.DeclaringType);
        ILGenerator
il = dynamic.GetILGenerator();
        il.DeclareLocal(target.DeclaringType);
        il.Emit(OpCodes
.Newobj, target);
        il.Emit(OpCodes
.Stloc_0);
        il.Emit(OpCodes
.Ldloc_0);
        il.Emit(OpCodes
.Ret);

        methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker
));
    }

    public
object CreateInstance()
    {
        return
methodHandler();
    }
}

ObjectCreateMethod inv = new ObjectCreateMethod(info);
o = null
;
watch.Start();
for (int
i = 0; i < 1000000; i++)
{
    o = inv.CreateInstance();
}
watch.Stop();
Console.WriteLine(string.Format("Method Invocation : {0} ms", watch.ElapsedMilliseconds));

When we run the code above, the output will be as follows:
Method Invocation : 27 ms.

Here in this example, we are creating an instance of DynamicMethod and fill DynamicMethod's body by using ILGenerator class. And in the IL, we use the Newobj-(Argument: Method Token)- OpCode (which means creating an instance of a Type) to create an instance, and than we return the created object to the caller. This is also what the new keyword does in the IL. So our performance will be as the same as the new keyword's performance. Also to use the DynamicMethod, we used CreateDelegate method of the DynamicMethod, which creates a new delegate which we can use to execute this method. By calling CreateInstance method in the ObjectCreateMethod class, our DynamicMethod is invoked and returns the result.

Finally as you see here, if you use DynamicMethod to create instances of a Type (if you don't know the exact type during coding, otherwise you can use new :) ) is the fastest way to create an instance of the object.

You don't need to write your own Dynamic method creator classes, you can use the ObjectCreateMethod instances in your applications. Of course this method is just for the constructors which has no parameters. If you want to run a constructor which takes parameters, then you have to write your own Dynamic Methods.

See you later ...

Download Test Codes  -  More about Dynamic Methods

Dünyayı Değiştirecek Altı Fikir

Amerikan Esquire dergisi "Six Ideas That Will Change the World" - "Dünyayı değiştirecek altı fikir" isimli bir makale yayınladı. Bu makalede beni hatta bizleri ilgilendiren önemli bir nokta vardı oda şu;
Derginin sıraladığı 6 fikirden 3. olanı yani "Pollution Magnet" bir Türk'ünde içinde bulunduğu bir ekip tarafından geliştirilmişti. Bu Türk'ün adı Cafer Tayyar YAVUZ. Ortaokulda bir süre beraber okuduğumuz, lise yıllarında TÜBİTAK Kimya Olimpiyatlarına beraber katıldığımız daha sonra beni bir gece operasyonu ile beni Bilkent Kimya'ya gönderip kendi ODTÜ'yü tercih eden, orayı 3 yıl gibi rekor bir sürede bitirip Amerika'ya Rice Universitesi'ne giden çok ama çok sevdiğim bir arkadaşım ve hatta kardeşim.
More...

At last

Since blogs have started to spread as mushrooms in the world of web, I have been thinking about creating my own blog which I can use as a sharing point of some useful and functional codes, ideas, theories about .NET and C#. My aim is not only sharing codes, but also making some discussions inside the depths of the .NET with the people of the .NET, but something always happened to prevent me from creating my own blog space through all these times. Although I persuaded myself that I couldn’t open my blog because of "business", "time limitation", etc., I know the real reason has been laziness.
More...

Search

Calendar

<<  September 2010  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
View posts in large calendar

Disclaimer

© 2007 - 2009
Ozcan DEGIRMENCI
All rights reserved. The content can be used elsewhere given that the source is properly acknowledged.