locked
What is the key difference between class and structs?

    General discussion

  • What is the key difference between class and structs?
    Wednesday, July 11, 2012 5:36 AM

All replies

  • class is reference type

    struct is value type

    Wednesday, July 11, 2012 8:46 AM
  • In which situation we have to use class

    and in which situation we have to use structs.

    Please clear :(

    Wednesday, July 11, 2012 10:18 AM
  • Hi,

    Check the below link for more details http://msdn.microsoft.com/en-us/library/2hkbth2a(v=vs.80).aspx


    PS.Shakeer Hussain

    Wednesday, July 11, 2012 10:23 AM
  • Assigning a struct instance to another struct instance copies the struct - for classes, the instances will be the same object after an assignment.


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Wednesday, July 11, 2012 7:58 PM
  • When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.

    A struct is normally used for pure data constructs, and a class for objects with operations.
    Wednesday, July 11, 2012 8:59 PM
  • When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.

    A struct is normally used for pure data constructs, and a class for objects with operations.
    Value types don't always go on the stack.
    Wednesday, July 11, 2012 9:18 PM
  •        

    Structs are ValueTypes
    Classes are ReferenceTypes

    Structs can't inherit from anything else than System.ValueType
    Classes can inherit from (almost) any base class.

    Structs can not serve a base type for derived types.
    In consequence, structs methods are not permitted to be marked protected, protected internal, virtual, abstract or sealed.
    Classes can be used as base classes (unless they're sealed).


    Structs "exist" through declaration, intantiation is optional.
    Classes need intantiation - usually they're created through the "new" keyword or an Activator.

    Structs are said to be stored on the stack when they're local variables and on the managed heap when they're fields or lambda variables.
    Class instances are said to be always stored on the managed heap. (Although these implementation details are not guaranteed, not part of the official .NET docs and that programmers should not rely on, according to E.Lippert)

    All fields of a struct need to get initialized explicitly - in the body of a structs non-default constructor.
    Struct fields however can't get initialized directly on declaration (C# spec 11.3.7).
    Class fields are always initialized with defaults implicitly. They may or may not be initialized directly.
    They may or may not be initialized inside default and non-default constructors.

    A default c'tor can't be declared for structs.
    Declaring an non-default c'tor doesn't remove the implicit default c'tor of the struct.
    A default c'tor can be declared for classes.
    Declaring an non-default c'tor removes the implicit default c'tor of the class.

    A destructor can't be declared for structs.
    A destructor can be declared for classes.

    Because they are value types, the whole data of a struct gets copied on assignment and also when being passed as a byval parameter.
    Thus structs are recommended to be tiny "objects" that only contain a few fields.
    When assigning a class instance to a variable or byval parameter only a new reference is created, which references the same object in memory - so using classes is often more performant and consumes less memory than using structs.

    Structs can not be extended by Extension methods.
    Classes can be extended by Extension methods.

    "struct" can not be used as a generic constraint keyword.
    "class" can be used as a generic constraint keyword.

    Each struct type can be used as a TypeParameter for a SystemNullable<T>.
    No class type can be used as a TypeParameter for a SystemNullable<T>.

    Structs are often better suited as datacontainers when doing interop with Win32 / PInvoke.

    Structs will get boxed when being passed as  / casted to System.Object (performance issue).

    The default implementation of the Equals method performs a value based comparison for Structs.
    The default implementation of the Equals method performs a reference comparison for Classes.

            struct A { public int Value; }
            class  B { public int Value; }
    
            static void Main(string[] args)
            {
                A a1, a2;                               
    a1.Value = 1; a2.Value = 1;
    var same1 = Equals(a1, a2); // true
    B b1 = new B(), b2 = new B();
    b1.Value = 1; b2.Value = 1;
    var same2 = Equals(b1, b2); // false }

    Structs have no identity. ReferenceEquals will always return false for two struct variables, whether they hold the same data or not and also if a struct varaible is compared to itself.
    Classes have identity. ReferenceEquals will always return true for two different class variables that refer to same instance.    

            
            static void Main(string[] args)
            {
                A a1;
                a1.Value = 1;
                A a2 = a1;
                var same1 = ReferenceEquals(a1, a2); // false
    var same0 = ReferenceEquals(a1, a1); // also false B b1 = new B(); b1.Value = 1; B b2 = b1; var same2 = ReferenceEquals(b1, b2); // true }

    Chris

    Wednesday, July 11, 2012 10:12 PM
  • @Christian, you've rattled off a lot of the symptoms of differences between structs and classes without actually discussing the root difference.

    When you have a variable that is a value type, the variable is holding onto the actual object/data itself.  For a reference type the actual object is stored "somewhere else" and the variable only contains a reference (sometimes called a pointer) to that object.

    Classes are reference types, and structs are value types.

    Pretty much all of those differences are just symptoms of that root difference.

    Local variables are usually stored on the stack, so local variables that are structs generally result in the actual struct object being stored on the stack.  For classes the reference to the actual object is stored "somewhere else" (that somewhere being the heap) and the reference to that object is stored on the heap.

    When you copy a variable that is a struct, since that variable is the struct, the struct is copied.  When you copy a variable that is a class, that variable is just a reference to the object, not the object itself, so just that reference is copied.

    As long as you learn to think in this way everything else just makes sense and you don't need to sit down and remember a list of 3 dozen differences between classes and structs.  There is only one.

    Thursday, July 12, 2012 2:52 PM