Object size in memory c#

Unfortunately there is no direct way to do it. Speacialy for the managed code. May you can use memorystream and serialization for getting an idea but this are not actual size of your object. You may use some solution below for calculation actual size.

GC
One way is to use the GC.GetTotalMemory method to measure the amount of memory used before and after creating your object. This won’t be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Source :http://stackoverflow.com/questions/605621/how-to-get-object-size-in-memory

Using Strike or SOS Debugging Extension (SOS.dll)
use : DumpHeap [-stat] [-min <size>][-max <size>] [-thinlock] [-mt <MethodTable address>] [-type <partial type name>][start [end]]

Displays information about the garbage-collected heap and collection statistics about objects.
The DumpHeap command displays a warning if it detects excessive fragmentation in the garbage collector heap.
The -stat option restricts the output to the statistical type summary.
The -min option ignores objects that are less than the size parameter, specified in bytes.
The -max option ignores objects that are larger than the size parameter, specified in bytes.
The -thinlock option reports ThinLocks. For more information, see the SyncBlk command.
The -mt option lists only those objects that correspond to specified the MethodTable structure.
The -type option lists only those objects whose type name is a substring match of the specified string.
The start parameter begins listing from the specified address.
The end parameter stops listing at the specified address.

!dumpheap -stat
Note that !dumpheap only gives you the bytes of the object type itself, and doesn’t include the bytes of any other object types that it might reference

More Info:
http://msdn.microsoft.com/en-us/library/bb190764.aspx

3rd party solutions

Using .Net Memory Profiler (Easy way)
http://memprofiler.com/download.aspx

using CLR Profiler (free)
http://www.microsoft.com/downloads/details.aspx?familyid=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en

ANTS Memory Profiler
http://www.red-gate.com/products/ants_memory_profiler/index.htm

Note:
Some people have confused the System.Runtime.InteropServices.Marshal.SizeOf() service with this API.  However, Marshal.SizeOf reveals the size of an object after it has been marshaled.  In other words, it yields the size of the object when converted to an unmanaged representation.  These sizes will certainly differ if the CLR’s loader has re-ordered small fields so they can be packed together on a tdAutoLayout type.
source : http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

code bye…

How to set a default property for your class

I’m sorry but that functionality which is known by vb developers couldn’t possible when you are codding in c# .
Also there are some other solutions but its not possible to set a default property for your your class.

you can use indexer but its not that we want:

public string this[int idx]
{
get { … }
set { … }
}

or you can overload  implicit operator to do this but  is also not suggested.


[System.Diagnostics.DebuggerDisplay("{Value}")]
public class MyClass
{

public string Value { get; set; }
    public static implicit operator MyClass(string s)
    {
        return new MyClass { Value = s };
    }

    public static explicit operator string(MyClass f)
    {
        return f.Value;
    }
    public override string ToString()
    {
        return Value;
    }
}

 

HttpHandler content-type as xml

        XmlNode xml = e.Xml;

        this.Response.Clear();

        string strXml = xml.OuterXml;
        this.Response.AddHeader("Content-Disposition", "attachment; filename=submittedData.xml");
        this.Response.AddHeader("Content-Length", strXml.Length.ToString());
        this.Response.ContentType = "application/xml";
        this.Response.Write(strXml);

        this.Response.End();

Thread Safe Invoke Functions

Download Project
Every developer who using threads  encounter with Illegal Cross Thread operations. And they solve this probles with creating delegate functions and invoking by other control. And this action cause writting more code. In this post i introduce you  an InvokeService classes that using methods with threadsafe operations.

Before this we make a method thread safe like this and think about all methods you do it like this way it causes lots of codes:

       //This code is not nessasary now
        public delegate void AppendTextDelegate(string text);
        public void GetSomeOutsiteData(string data)
        {
            this.Invoke(new AppendTextDelegate(AppendText), data);
        }
        //The method that use for thread safe
        public void AppendText(string text)
        {
            textBox1.Text += text + Environment.NewLine;
        }

Now just one line:

Instance.RegisterThreadSafeWatcher("AppendText", this,(Delegatenew Server.DataRecievedDelegate(AppendText));

Usage :

“Test” Class
First you create a business class that  inherits  form “InvokableBase”.And two sample delegate method that used by this class.Also this class contains a different thread for doing its jobs will cause “Cross Thread operation”.For doing this we use Invoke() function of  base class of InvokableBase

    class Test:InvokableBase,IDisposable
    {
        public delegate void TextDelegate(string text);
        public delegate void IntDelegate(int text);
        Thread a = null;
        public void DoSomething()
        {
           a = new Thread(new ThreadStart(worker));
            a.Start();
        }
        public void worker()
        {
            for (int i = 0; i < 10; i++)
            {
                string text = "Hello World";
                base.Invoke(typeof(TextDelegate), text);
                Thread.Sleep(1000);
            }
            for (int i = 0; i < 10; i++)
            {
                base.Invoke(typeof(IntDelegate), i);
                Thread.Sleep(1000);
            }
        }

A Windows Form Class This class can used by main thread for complete its GUI operations. Test class sends text and integer data to this form class and this forms safely prints it into a multiline textbox and using InvokeService prevents errors of cross thread operations.

        Test cls =null;
        private void button1_Click(object sender, EventArgs e)
        {
            cls = new Test();
            cls.RegisterThreadSafeWatcher("AppendText", this,(Delegate) new Test.TextDelegate(AppendText));
            cls.RegisterThreadSafeWatcher("AppendInt", this, (Delegate) new Test.IntDelegate(AppendInt));
            cls.DoSomething();
        }
        public void AppendText(string value)
        {
            textBox1.Text += value + Environment.NewLine;
        }
        public void AppendInt(int value)
        {
            textBox1.Text += value.ToString() + Environment.NewLine;
        }
        private void TestForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            cls.Dispose();
        }
You can download full project from this link:
http://rapidshare.com/files/308290393/InvokeService.rar
Have a nice coding !

Remove last character using TrimEnd()

You somehow create  an array using a loop  and want to sperate items with comma or etc. but everyone knows the last char of this array is one of that comma and unwant.You have to remove it. Usually we do this like

string mystring = “some,thing,in,this,array,”;

   mystring = mystring.Substring(0, mystring.Length - 1);

this is correct bu there is an easy way to do it:

   mystring = mystring.TrimEnd(',');