C# programming -> structure  
Author Message
DEEPAK GARG





PostPosted: Visual C# General, C# programming -> structure Top

HI

why we can't initialize the variable inside the structure.



Visual C#7  
 
 
Mattias Sjogren





PostPosted: Visual C# General, C# programming -> structure Top

Because field initializers are effectively moved to a contructor, but you can't have a parameterless constructor in structs. You can define an explicit constructor with parameters and put the initialization code there.



 
 
DEEPAK GARG





PostPosted: Visual C# General, C# programming -> structure Top

Hi

I have so many Query regarding structure in c#. please explain all these question in a descrptive way.

1. when to use structure Can any one explain me with real time example.

2. how structure is value type how we come to know that particular type is value or reference. Is there any criteria to identify the value type and reference type

3. why we cant initialize the variable inside the structure. Is it something related to value type. but we can initialize the variable inside the class

4. Why we can't create the parameterless(default) constructor inside the structure.

5 A struct cannot inherit from another struct or class, and it cannot be the base of a clas why

6.why we can't declare destructor inside the strcuture.

7.why it is necessary to set all the declared variables of structure while declaring the parameterised constructor

with regards

Deepak

.


 
 
Mattias Sjogren





PostPosted: Visual C# General, C# programming -> structure Top

1. For small, often immutable, data types where you want value assignment semantics (ie when you want an assignment to make a copy of the value, not just copy a reference). Or when you for interop purposes want to model a Win32 struct.

2. It just is. If you look in the documentation or with a tool like Object browser and see that the base type is System.ValueType or System.Enum, it is a value type. At runtime you can check with System.Type.IsValueType.

3. See my reply to your earlier thread.

4. The short answer is that it wouldn't be guaranteed to always be called.

5. Probably mostly for the sake of simplicity. If you need inheritance it's a sign you should go with a class instead.

6. Because value type instances are not garbage collected objects (at least not in themselves, only when part of another object), there's nothing to call the finalizer / "destructor".

7. The instance must be fully initialized when you leave the constructor - that's a feature of the C# programming language. You don't necessarily have to assign each member separately. You can init the entire instance to the default (zeroed out) value by assigning to 'this'.



 
 
Figo Fei - MSFT





PostPosted: Visual C# General, C# programming -> structure Top

I merged.