Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

- - - - -

Understanding the differences between a class and struct in C# :


  • Please log in to reply
7 replies to this topic

#1 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 04 April 2008 - 12:37 PM

Understanding the differences between a class and struct in C# :

If you are not an experienced programmer, you might be confused by the classes and the structs. Assuming that you might be already a little confused by the differences between function and classes, we will try to explain in detail the structs here.


Struct: Doesn't hold a value;
Class: Holds a value

Garbage collection:
As you probably know one of the major difference between C# and C++ is how the developer manages memory. In C# the memory is easily allocated by the garbage collector. Now, however this is partly true, because when we work with structs the memory is not directly allocated unless you use reference types and these types refer to a real value that invokes the garbage collector.

The This KEYWORD, WHEN working with structs:
In the classes the "this" keyword always defines a value, it cannot be used with keywords ref and out. Consider the following example, it will produce a compiler error. So you better don't try to remember it...:

class demonclass
{
    //...
    public void Method(demonclass that)
    {
        RefParameter(ref this); // compile error
        OutParameter(out this); // compile error
        this = that;            // compile error
    }
    //...
}
The right implementation when we use struct:

struct theright
{
    //...
    public void Reassign(theright that)
    {
        RefParameter(ref this); // compiles ok
        OutParameter(out this); // compiles ok
        this = that;            // compiles ok
    }
    //...
}
A struct can be used even in cases with readonly values, consider the following example:



struct theright
{
    public theright(int value)
    {
        Field = value;
    }
     
    public void Reassign(theright that)
    {
        RefParameter(ref this); // compiles ok
        OutParameter(out this); // compiles ok
        this = that;            // compiles ok
    }
    
    public readonly int Field;
}

class justaclass
{
    static void Main()
    {
        theright s = new theright(112);
        Console.WriteLine(s.Field); // the output is 112
        s.Reassign(new theright(24));
        Console.WriteLine(s.Field); // the output is 112
    }
}

Another major difference is that a class might design its objects as private and hence they might not be accesed further in the program. On the other hand the objects are always public.

The struct cannot be null:
using System;

class Nullclass
{

    static void Eg(int? x)
    {

        if (x != null)
        {
            Console.WriteLine("This is OK");// ok
        }

    }
    public static void Main()
    {

    }
}

If everything went right you should see nothing on your screen...but only the empty prompt when you start it without debugging:

Posted Image


Can the struct use destructors?
NO. Because they don't need to, since they don't use the memory allocation, garbage collectors and so on.


How a class handles inheritance and how a struct handles inheritance:
The structs are sealed, the classes are not.
The class can't be abstract. The class could be abstract(meaning that the class can be used as a parent class).
The structs cannot use the base() method. The classes can.
The structs cannot extend other structs, and the classes can extend classes.
Protected members can't be declared within structs. The classes can declare such members(objects).
a struct can't declare abstract function members, an abstract class can.
The struct can't declare abstract, virtual and sealed functions. The classes can do that...

Edited by Jordan, 04 April 2008 - 12:42 PM.

  • 0

#2 morfec

morfec

    CC Lurker

  • Just Joined
  • Pip
  • 7 posts

Posted 18 April 2008 - 02:23 AM

thanks thanks thanks
  • 0

#3 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 19 April 2008 - 05:33 AM

I tend to use structs, as they are generally easier to make. However, for bigger projects, classes are the way to go.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#4 gaylo565

gaylo565

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 258 posts

Posted 19 April 2008 - 10:21 PM

I find structs useful for structuring data in useful ways when simple arrays wont do the trick, but for most things a class is more versatile. No destructors is a nice touch for structs though...Writing less code is always a plus if you have limited needs.
  • 0

#5 Xav

Xav

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 8356 posts

Posted 20 April 2008 - 06:32 AM

There's not necessarily a problem with more code, although it can become difficult to manage. Which is partially why classes were invented.
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#6 DellMercant

DellMercant

    CC Lurker

  • New Member
  • Pip
  • 3 posts

Posted 13 July 2015 - 09:41 PM

Technically speaking, structs and classes are almost equivalent, still there are many differences. The major difference like class provides the flexibility of combining data and methods (functions ) and it provides the re-usability called inheritance. Struct should typically be used for grouping data. The technical difference comes down to subtle issues about default visibility of members. Here you can see some of the Difference between Class and Structure.

 

Dell


Edited by WingedPanther73, 14 July 2015 - 04:25 AM.
delete spammy link

  • 0

#7 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 14 July 2015 - 04:25 AM

Dell, you realize you kind of said what the original poster did, right?


  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#8 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts
  • Programming Language:C, C++, C#, JavaScript, PL/SQL, Delphi/Object Pascal, Visual Basic .NET, Pascal, Transact-SQL, Bash

Posted 14 July 2015 - 06:05 AM

Technically speaking, this thread has been dead for 7 years  :eek:

 

tallahasse_zombie_thread.jpg

 

If you want to nitpick, the line:

 

if( x != null )

 

should be:

 

if( x.HasValue )


  • 1
My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth