Struct

  • What is Struct?
    A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.
    When an object is created from a struct and assigned to a variable, the variable contains the complete value of the struct.
  • When a variable that contains a struct is copied, all the data is copied, and any modification to the new copy does not change the data for the old copy. Because structs do not use references, they do not have identity; you cannot distinguish between two instances of a value type with the same data.
    Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
    Structs have the following properties:
    · Structs are value types and classes are reference types.
    · Unlike classes, structs can be instantiated without using a new operator.
    · Structs can declare constructors, but they must take parameters.
    · A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
    · A struct can implement interfaces.
    · A struct can be used as a nullable type and can be assigned a null value.
    What are the limitations of struct than classes?
    · Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
    · A struct may not declare a default constructor (a constructor without parameters) or a destructor.
    · Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
    Why A struct does not declare a default constructor?
    Because copies of structs are created and destroyed automatically by the compiler, a default constructor and destructor are unnecessary. In effect, the compiler implements the default constructor by assigning all the fields of their default values.
    Explain similarities between class and struct ?
    Structures and classes are similar in the following respects:
    · Both are container types, meaning that they contain other types as members.
    · Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and event handlers. However, do not confuse these members with the declared elements of a structure.
    · Members of both can have individualized access levels. For example, one member can be declared Public and another Private.
    · Both can implement interfaces.
    · Both can have shared constructors, with or without parameters.
    · Both can expose a default property, provided that property takes at least one parameter.
    · Both can declare and raise events, and both can declare delegates.
    What are the differences between class and struct?
    Structures and classes differ in the following particulars:
    · Structures are value types; classes are reference types. A variable of a structure type contains the structure's data, rather than containing a reference to the data as a class type does.
    · Structures use stack allocation; classes use heap allocation.
    · All structure elements are Public by default; class variables and constants are Private by default, while other class members are Public by default.
    · A structure must have at least one nonshared variable or nonshared, noncustom event element; a class can be completely empty.
    · Structure elements cannot be declared as Protected; class members can.
    · A structure procedure can handle events only if it is a static method, and only by means of the AddHandler Statement; any class procedure can handle events, using either the Handles keyword or the AddHandler statement.
  • · Structure variable declarations cannot specify initializers or initial sizes for arrays; class variable declarations can.
    · Structures implicitly inherit from the System..::.ValueType class and cannot inherit from any other type; classes can inherit from any class or classes other than System.ValueType
    · Structures are not inheritable; classes are.
    · Structures are never terminated, so the common language runtime (CLR) never calls the Finalize method on any structure; classes are terminated by the garbage collector (GC), which calls Finalize on a class when it detects there are no active references remaining.
    · A structure does not require a constructor; a class does.
    · Structures can have nonshared constructors only if they take parameters; classes can have them with or without parameters.
    Every structure has an implicit public constructor without parameters. This constructor initializes all the structure's data elements to their default values. You cannot redefine this behavior
    Instances and Variables:Because structures are value types, each structure variable is permanently bound to an individual structure instance. But classes are reference types, and an object variable can refer to various class instances at different times. This distinction affects your usage of structures and classes in the following ways:
    · Initialization. A structure variable implicitly includes an initialization of the elements using the structure's parameterless constructor. Therefore,
  • struct s ; is equivalent to struct s1 = new struct() ;
    · Assigning Variables. When you assign one structure variable to another, or pass a structure instance to a procedure argument, the current values of all the variable elements are copied to the new structure. When you assign one object variable to another, or pass an object variable to a procedure, only the reference pointer is copied.
    · Assigning Nothing. You can assign the value " null" to a structure variable, but the instance continues to be associated with the variable. You can still call its methods and access its data elements, although variable elements are reinitialized by the assignment.
    In contrast, if you set an object variable to " null ", you dissociate it from any class instance, and you cannot access any members through the variable until you assign another instance to it.
    · Multiple Instances. An object variable can have different class instances assigned to it at different times, and several object variables can refer to the same class instance at the same time. Changes you make to the values of class members affect those members when accessed through another variable pointing to the same instance.
    Structure elements, however, are isolated within their own instance. Changes to their values are not reflected in any other structure variables, even in other instances of the same Structure declaration.
    · Equality. Equality testing of two structures must be performed with an element-by-element test. Two object variables can be compared using the Equals method. Equals indicates whether the two variables point to the same instance.
    When to choose struct instead of class?
    Classes are reference types and structures are value types. Reference types are allocated on the heap, and memory management is handled by the garbage collector. Value types are allocated on the stack or inline and are deallocated when they go out of scope. In general, value types are cheaper to allocate and deallocate.
    Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
    Do not define a structure unless the type has all of the following characteristics:
    · It logically represents a single value, similar to primitive types (integer, double, and so on).
    · It has an instance size smaller than 16 bytes.
    · It is immutable.
    · It will not have to be boxed frequently.
    If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.

Will the following code compile?

using System;

public class Example

{

static void Main()

{

TestStruct T = new TestStruct();

Console.WriteLine(T.i);

}

}

public struct TestStruct{public int i=10;//Error: cannot have instance field initializers in structs}

Ans:No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"

What is the base type from which all structs inherit directly?

All structs inherit directly from System.ValueType, which inherits from System.Object.

Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?

No

Can you instantiate a struct without using a new operator in C#?Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?

No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can a struct inherit from an interface in C#?

Yes

Classes and structs support inheritance. Is this statement true or false?

False, Only classes support inheritance. structs donot support inheritance.

Classes and structs can be declared as static, Is this statement true or false?

False, only classes can be declared as static and not structs.