Comments

You must log in or register to comment.

Zealous___Ideal t1_ixdafut wrote

Programming is tricky to explain to a 5 year old.

A class is like “all your toy trucks”

A constructor is “how does fisher-price make your trucks?”

Structs are a list of all the things on your truck: Its lights, its wheels, etc.

Methods are all the cool things your truck can do: Honk, back up, scare the dog.

5

km89 t1_ixdadxz wrote

A "class" is a group of related code, typically organized such that you can instantiate an "object". For example, you might have a Fruit class that contains all the methods and properties that a fruit can do (ripen, rot, color, etc).

A "method" is something that the object can do. As noted above, a Fruit class might have methods for ripening or rotting; these methods would contain the code necessary to manipulate the object to do those things.

A "property", which you didn't ask about but which is important, is something about the object--not something that it can do, but something about its current state. A Fruit's Color property (Fruit.Color, for example) could be set to red, or orange, or yellow, or whatever else.

Here's an example of how properties and methods can work together.

 class Program{
      public static void main(String[] args){
           Fruit banana = new Fruit(); //This calls the constructor, which currently doesn't do anything.
           banana.Color = "Green"; //Sets the Color property of the Fruit object to green.

           banana.Ripen(); //Calls the Ripen method, which for the sake of argument here changes the color

           Console.WriteLine(banana.Color); //Would write to the console the color of the fruit. 
                                                 //For the sake of argument, assume the Ripen() method 
                                                 //changes the color from green to yellow, so this would 
                                                 //write out "Yellow" to the console.
      }
 }

When you first instantiate an object, you call that object's "constructor". A constructor is a special method that contains all the logic needed to set the object up initially, before you begin to do anything with it. This will get slightly more technical, but imagine this:

 class Recipe{
      private List<string> ingredients;
      
      Recipe(){
           ingredients = new List<string>();
      }
 }

Above, the Recipe class has a private List of ingredients (and it's declared with List<string> because the List class can be of any type, so you're telling the compiler that all of the stuff in this List will be of the string data type). It's private, because nothing should be able to directly access it. But, also notice how it's not actually instantiated. The constructor, which is the one method in this class, instantiates the List object. An actually useful class would also have methods for getting and setting the ingredients, but they're not listed here.

Constructors are occasionally paired with "destructors." A destructor is another special method that handles any logic the object needs to do before it goes away. If you don't manually declare one, the compiler will put a fake one in for you, so don't worry about these unless you have to.

Structs are different from classes. They share a lot of similarities, but ultimately they're more limited and less able to change. The big difference is that they're not really objects and thus shouldn't--or can't--be changed after creating them, and they can't be used to inherit from.

Here's a good link that has a rundown of the differences between structs and classes, which I'll link rather than just typing out the differences here.

>https://www.c-sharpcorner.com/blogs/difference-between-struct-and-class-in-c-sharp

2

oneeyedziggy t1_ixdasff wrote

So think of classes as representing a thing... Like pie. You can make a new pie and it's not the class itself, but it is A pie.

Constructors are like a method that runs upon making a new pie... Set the flavor, crust type, size, et cetera.

Methods are things the pie does (the metaphor is breaking down a bit, but stay with me)... A pie might have an "eat" method that subtracts from it's current amount and returns a text description of the subtle flavor notes... Or maybe a specific message for the last slice about how uncle marvin was pissdd because he was saving that piece for your aunt. (so, like a function that belongs to a class)

I'm not a C# dev so while the rest may be close enough, Imma have to just have a go at describing structs: I'm pretty sure they just typed sets of properties... Like a class without methods... Like you might instead make a pie struct (because honestly, pies probably don't need methods, they don't DO a lot, and they're probably not dynamic or complex enough to need a constructor) so then you just make a "feast" class that has a bunch of food struct-typed properties with single eat method that takes the name of a food and subtracts from its quantity

2

Triabolical_ t1_ixg5avj wrote

>I'm not a C# dev so while the rest may be close enough, Imma have to just have a go at describing structs: I'm pretty sure they just typed sets of properties... Like a class without methods... Like you might instead make a pie struct (because honestly, pies probably don't need methods, they don't DO a lot, and they're probably not dynamic or complex enough to need a constructor) so then you just make a "feast" class that has a bunch of food struct-typed properties with single eat method that takes the name of a food and subtracts from its quantity

Structs are value types, while classes are reference types.

Structs exist in C# so that you can easily implement types with value semantics - like a bignum class - and to do interop with windows system APIs that were written with C and therefore require a very specific memory layout.

Struct *mostly* operate like classes; both can have methods with them.

1

oneeyedziggy t1_ixgd04t wrote

Huh... TIL... you'd think rather than coming up with a whole new name they'd just add another declaration keyword to do whatever the non-default thing is...

1

Triabolical_ t1_ixigt2n wrote

I was the test lead for the C# compiler and spent a lot of time in design meetings...

"class" and "struct" come from C++ though there they only have a difference in visibility, not in behavior.

"class" is the obvious choice for the main construct as that's what's used in many other languages.

Then we needed a name for something that's kindof like a class but not the same thing. It turns out that coming up with names for things in languages is really hard, as many of the non-reserved words are already used by programmers in a lot of cases. C# was a new language at that time but there were already developers writing the base class libraries in C# and their feedback was "don't take away names from us".

They were virtually all C++ developers, and nobody who writes C++ code was going to call something "struct" because it was a reserved word, so it was available, and we wanted something very distinct from "class" because the intended usage was so different.

That was a pretty early decision during language design.

Later the team came up with the concept of "conceptual keywords" - keywords that were reserved but only in specific situations. The words "get" and "set" for properties are a good example of that. If we'd done that earlier, we might have done something different with struct though I think we probably would have stuck with it as a name.

Not that the conceptual difference between classes and structs isn't quite confusing and very different than how C++ views the world, but that was inherently going to happen moving from an unmanaged to a managed world.

Thanks for letting me take a trip back on memory lane.

2

oneeyedziggy t1_ixilahp wrote

Awesome context... As I'm not a c# dev (well, my professional use of c# was extremely short lived and 10+ years ago...)... I was thinking in terms of what little java I know (also not a java dev) but how basically all options 9n a variable are enumerated in long-form when declaring ( public static String blah blah...) and just imagining (naively, based on the previous comment) that it might have been as simple as adding a byref or byval to the string of qualifiers when using a class to get struct behavior (and defaulting to some sane default where omitted)... Is this even relevant to the situation either in c# having such qualifiers or in classes and structs being sufficiently similar for that to be feasible (if only everything had been different)?

1

Triabolical_ t1_ixjwabm wrote

> Is this even relevant to the situation either in c# having such qualifiers or in classes and structs being sufficiently similar for that to be feasible (if only everything had been different)?

C++ is pretty much that way; structs and classes are mostly the same thing and the developer chooses whether they want to allocate it on the stack or whether they want to put it in dynamic memory.

In C# - and managed languages in general - class instances are always allocated in dynamic memory. Structs were really just added for windows interop, though they do have other limited uses.

2

anotherlolwut t1_ixdatkw wrote

Start with a Struct. That's the most basic part.

A Struct is kind of like an array. It's a bundle of data all stored right next to each other in memory, but it doesn't all have to be the same kind of data. You can have a character array, an int, and a float all be part of a single Struct.

My Reddit info can be represented as a Struct (though you wouldn't do it unless you were working in plain C). I have a user name (character string), a number of posts (int) and an account age (double, representing years).

A Class is like a Struct, but it can perform functions. The functions are part of the data stored in that object. Classes have done other features that Structs don't, but basically, think of it as Struct with functions.

As a Reddit user, I can make a post. You could resident this as RedditUser.makePost(). The benefit of this over just using regular functions in C is that makePost() can know the data in RedditUser, so I don't always need to pass it things like my user name.

Now, Reddit has a bunch of users. Like a dozen or so. When someone logs in and wants to make a post, Reddit has to create an object for them to gather their profile info and allow them to do stuff. It might load user profile data from a big database and read it through a Class called RedditUser. The function that does that is a Constructor, and it is part of the RedditUser Class.

Basically, RedditUser knows how to accept some set of data and assign it to the properties of the Class (the character string for my user name, the int for the number of posts I've written, etc.).

A single Class can have lots of Constructors to be ready for any kind of incoming data, like if it gets to read the big Reddit database or if I'm making a post as an unregistered guest.

2

Triabolical_ t1_ixg5ier wrote

>A Class is like a Struct, but it can perform functions. The functions are part of the data stored in that object. Classes have done other features that Structs don't, but basically, think of it as Struct with functions.

Structs in C# have functions.

The big difference is that structs have value semantics and classes have reference semantics (almost always with very rare exceptions)...

3

lobsang_ludd t1_ixdcsy2 wrote

Struct: a bundle of data combining some set of named fields of different (potentially overlapping) types. It models an "AND" relationship between its fields, asserting that at some point in the system state they were all true together. It has no behaviour, and its data cannot be changed - although you can make a copy with a different value in a particular field.
Class: A bundle of data with behaviours. It has some set of methods that can be used to act on it, changing the data in accordance with the rules defined by its programmers. Classes can have an inheritance hierarchy, where instances of a derived class can use code from the parent class or an override method in their own class.

Constructor: A special case of the methods of a class, which is run when a new instance of the class is made. It's generally responsible for ensuring the assumptions made by other methods will be true.

2

Triabolical_ t1_ixg5kej wrote

Both structs and classes in C# have methods.

This is true in C++ as well.

2

Triabolical_ t1_ixg4zlo wrote

class vs struct

Structs are designed for very limited scenarios.

For what are called "value types" - types that behave like numbers or strings. They behave in the ways that we expect numbers to behave.

When you want to use system functions that expect a very specific layout of data in memory. I Windows, this is typically system stuff that is written with C or C++.

Unless it's one of those cases, you shouldn't use structs. You should use classes.

method vs constructor

Consider this code (written from memory, so it might have some errors ):

class MyNumber
{
private _number;

public MyNumber (int number) // constructor
{
_number = number;
}

public void PrintNumber()
{
Console.WriteLine(_number);
}
}

This class stores and prints out a number.

When this class is used, we always want it to have a number associated with it rather than a default value. If we try to write this:

MyNumber number = new MyNumber();

the compiler will complain. We need to write:

MyNumber number = new MyNumber(1345);

That ensures that instances of the class are in a known state - that is why we want to use constructors.

In this example, PrintNumber() is a method. It's not special the way a constructor is.

Hope that helps.

&#x200B;

&#x200B;

&#x200B;

Methods are chunks of code that are associated with a specific class. The important part of a method is that it has access to the private class variables associated with a method

2

Truen1ght t1_ixg95ul wrote

CLASS vs STRUCT

------------------------------

A class is a file that contains a bunch of operations it can perform, and a bunch of things it contains. The operations it can perform are called "methods" or "functions" (both are accurate, but maybe you've only heard one of the two terms. they are interchangeable).

By default, most things within a class have private scope, meaning only the class itself can perform operations listed within the class, or access/edit the things it contains.

A struct is nearly the same thing as a class, but by default everything is publicly scoped. That means that things outside of this class can perform the operations listed by the struct, or access/edit the things held by the struct.

So, truthfully, there are only 2 real differences between the struct and the class :

  1. using either the keyword "struct" or "class"
  2. the default scoping. public for a struct, private for a class.

So why are there two things? The struct came first from way back when, long before C# ever existed. The class came later, when people became better programmers and decided "yeah, maybe by default I should hide stuff from other structs/classes so that I'm less likely to accidentally change something I shouldn't". The struct is a holdover from original C.

&#x200B;

CONSTRUCTOR and DESTRUCTOR

----------------------------------

A constructor is a special method that all classes and structs have. If you do not explicitly declare this method within your class or struct, there is a default constructor that is provided instead. You cannot have a class or struct without a constructor method, because then there is no way for your program to create that class or struct before you would try to use it.

The job of the constructor is solely for creating your class or struct.

The opposite of the constructor is the destructor. Like the constructor, your class or struct must have one, and if you don't declare it explicitly within your class/struct, a default one is provided for you.

The job of the destructor is to delete the class/struct you created earlier, so that the memory it used while your program was running doesn't stay allocated. You may have heard the term "memory leak", that is what a destructor is meant to prevent. If you "leak" enough memory, eventually your computer will become unresponsive because it has no available RAM to do things. The only way to resolve the problem in that case is to restart your computer, which automatically clears out everything in RAM, freeing it up for use.

&#x200B;

Hopefully this explains it well enough for you.

2

Alokir t1_ixege0v wrote

Think of a class as a concept in the real world, like Dog or Animal. A class contains all data definitions and functionality necessary to work with this concept.

The functionality that relates to these concepts are called methods. For example, a Dog can bark, walk and wiggle its tail.

If you want to talk about a specific Dog you use the Dog class as a blueprint and create a dog object. Each time this happens the constructor is called automatically, which is a special method that is meant to set the initial values for the newly created object.

A struct is a way to group data together, it's easier to handle than having many individual variables.

1