locked
Value Type vs Reference Type RRS feed

  • Question

  • Hi,

    why instance fields cann't be initialized inside a struct? and one more question

    System.object is the base class for all types if I declare a value type I mean struct , it must derived from system.object so reference types are accepting null why cann't i initialize null to value type?

    kindly any one please tell me why instance fields cann't be initialized

    Example:

    struct SampleStruct

    {

    internal int a;

    internal double d;

    }

    I have few ideas of

    ->value types are stored in stack and reference type are stored in heap and all.

    ->Value types has implicitly default constructor(parameter less constructor)

    ->without using new operator we can access struct (SampleStruct s;).when I access fields which is not initialized compiler is throwing error like "Use of unassigned variable". so if i want to use a field i must initialize the field.

    my suggestion is the above way let me initialize a field inside a struct if i didn't assign a field and i am trying to using that field you can show error at that time right?


    Monday, October 15, 2012 5:38 AM

All replies

  • Hi Friend,
       You are right... Base type of the types in .NET is System.Object. In case of ValueTypes, they are inherited from System.ValueType which is inturn inherited from System.Object. You can have a look to these hierarchy with the help of Object Browser in Visual Studio.

      Now you can make a value type to nullable using the new feature in .net.
    example: if you declare as int, it cannot hold any null value. But if you declare like ?int, you can have null values too. you may try the same in struct too. more information is available in the link below.

    http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx 
    http://msdn.microsoft.com/en-us/library/2cf62fcy(v=vs.80).aspx

    Regarding the storage, For all objects there will be a stack entry. For value types, this will be the value itself and for reference type, the address of the heap location where the value is, will be stored there(in stack).


    -- Thanks Ajith R Nair


    Monday, October 15, 2012 8:45 AM
  • Hi,

    Thanks for your help. still i have two question

    -> I can understand they have separate kind of value type to handle nullable type (int?). my question is why cann't they fix this with (int) itself. what is the issue with this?

    -> why can't i declare a default constructor?

    -> why instance fields cann't be initialized inside a struct?

    I am very eager to know this answer kindly help me.


    Monday, October 15, 2012 9:15 AM
  • Friend,
      Good question..You made me reading lot of blogs and article to confirm. thanks for that first. I would say, please go throught the links below, which will belp you strong in .NET memory management. As a hint i can tell you that,value types are in stack and it must have a value from 0 to its maximum capacity. There is no chance of null/empty there as it is binary. But in reference type, you can have the address in stack where it points to a location which virtually treats as null.

    http://www.yoda.arachsys.com/csharp/memory.html

    http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx


    -- Thanks Ajith R Nair

    Tuesday, October 16, 2012 9:43 AM
  • Thanks a lot dude. still searching and reading blogs to get answers for my question.

    -> why can't i declare a default constructor?

    -> why instance fields cann't be initialized inside a struct?

    Tuesday, October 16, 2012 12:43 PM
  • Dear friend... Why you need a default constructor for a valuetype in which the value is already initialized to a default value... Make sence?

    For struct, yes we can have constructors. Please find the link here : http://msdn.microsoft.com/en-us/library/aa288208(v=vs.71).aspx

    If the question is, how to instantiate a reference type in Struct constructor, please find the code below.

    class Program
        {
            static void Main(string[] args)
            {
                Point p = new Point(10, 20);
            }
        }
        public struct Point
        {
            public int x, y;
            public string Name;
            // Constructor:
            public Point(int x, int y)
            {
                this.x = x;
                this.y = y;
                Name = "Ajith Raveendran";
            }
            // Override the ToString method:
            public override string ToString()
            {
                return (String.Format("({0},{1})", x, y));
            }
        }
    In the above, the name is valuetype(string) and got initialized in constructor.

    -- Thanks Ajith R Nair


    • Edited by Ajith R Nair Wednesday, October 17, 2012 6:09 AM
    Wednesday, October 17, 2012 6:08 AM
  • Hi,

    kindly check this link dude. one sentence is saying

    "There are rare situations when the runtime must initialize a value type and is unable to call its default constructor. For example, this can happen when a thread local value type must be allocated and initialized when an unmanaged thread first executes managed code. In this situation, the runtime can't call the type's constructor but still ensures that all members are initialized to zero or null. For this reason, it is recommended that you don't define a parameterless constructor on a value type. In fact, the C# compiler (and others) consider this an error and won't compile the code. This problem is rare, and it never occurs on reference types. There are no restrictions on parameterized constructors for both value types and reference types."

    I cann't understand the above exactly and I don't know how this unmangaed thread won't affect reference type but it is affecting value type?

    Wednesday, October 17, 2012 6:16 AM