C
C#4mo ago
proc

Beginner question: classes and constructor code?

So I've read this section a few times and it is not going in. I understand declaring regular variables, but this page in my book is talking about "public class MyNumber" then later goes on to say MyNumber numb = new MyNumber, what is the purpose of this and what is going on? Why can't they just stick to int a = 123, what is the point in all this new class and horrible syntax?
34 Replies
proc
procOP4mo ago
It reminds me a bit of enums from C which I also hated I just found a really useful Youtube vid actually, it seems like classes are basically for times when an object requires more complexity than just 1 value, such as an employee, like employee ID, name, date of birth, etc - so that makes more sense now to me. Would appreciate any further input still if there's anything I should know...
Kouhai
Kouhai4mo ago
C# classes are very different from C enums The closest thing in C to C# classes are structs but they are still very different For why you use classes, pretty much for encapsulation
SleepWellPupper
SleepWellPupper4mo ago
Maybe an introduction to OOP would be helpful to you @proc Classes are a concept of Object Oriented Programming and are used to model, well, objects. There are more concepts that work off of that idea.
SleepWellPupper
SleepWellPupper4mo ago
Here's an official introductory tutorial on C# classes and how they relate to OOP: https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/classes
Classes and objects tutorial - C#
Create your first C# program and explore object oriented concepts
Becquerel
Becquerel4mo ago
a critical idea is that classes aren't just a way to bundle related values together. they also let you bundle behaviour alongside the values it operates on. that is, a class can 'own' functions/methods this makes it a lot easier to organise your codebase when you have 500 functions and 5000 bits of data floating around. with classes you can reasonably assume 'oh, the code for updating someone's username is probably in the User class'. it also means classes can hide away ugly implementation details from the rest of the world, and in turn the world doesn't have to care about how the User class works; it can just assume it does as for the 'MyNumber numb = new MyNumber()' stuff. this is actually very similar to 'int a = 123'. the only reason we don't have to repeat 'int' twice in that example is because ints are given special treatment by c# for convenience. it was done this way partially as a response to c++ (i think), where there are about 5000 ways to create a new object. many of which are not obvious at all. in contrast c# has the new keyword and nothing else, so it makes it very easy to tell when new objects are being made
proc
procOP4mo ago
Really useful feedback all - thanks for this, makes a lot of sense now. One thing I don't now understand, having read onwards a bit and also watched a few videos on the same topic - is the constructors. I don't see what the purpose is of declaring a new class with a few variables in it, then directly below is creating a constructor which is the same name, and then each individual variable with this.name = name, this.value = value, etc etc. All videos explain that this is necessary but doesn't really explain why they are doing it in the first place... For me it makes it appear very long-winded and of no purpose, as in the examples they are using you could probably create the same output with only a few lines of code (e.g. not even declaring a class, and only declaring variables by themselves). Is it meant to be for much larger programs that this becomes useful? Or is it really that tedious all the time?
blueberriesiftheywerecats
Imagine you are using someone's libraby and want to create some object from that library, how would you know what values should you provide for that object for proper initialisation? In this case you check constructor for more information Also you can provide in constructor something simple like int or string, but inside of that constructor you could create more complex objects out of more simple ones from it's parameters (sry for eng)
Angius
Angius4mo ago
Yes, constructors are very verbose, full agreement here. Thankfully, there are ways to reduce that verbosity. Take
public class Person
{
public string Name { get; }
public DateTime Birthday { get; }
public int ShoeSize { get; }

public Person(string name, DateTime birthday, int shoeSize)
{
Name = name;
Birthday = birthday;
ShoeSize = shoeSize;
}
}
public class Person
{
public string Name { get; }
public DateTime Birthday { get; }
public int ShoeSize { get; }

public Person(string name, DateTime birthday, int shoeSize)
{
Name = name;
Birthday = birthday;
ShoeSize = shoeSize;
}
}
we can use a primary constructor instead
public class Person(string name, DateTime birthday, int shoeSize)
{
public string Name { get; } = name;
public DateTime Birthday { get; } = birthday;
public int ShoeSize { get; } = shoeSize;
}
public class Person(string name, DateTime birthday, int shoeSize)
{
public string Name { get; } = name;
public DateTime Birthday { get; } = birthday;
public int ShoeSize { get; } = shoeSize;
}
or we could skip the constructor altogether, ensure that our properties are given a value without it thanks to the required keyword, and use the initializer syntax instead:
public class Person
{
public required string Name { get; init; }
public required DateTime Birthday { get; init; }
public required int ShoeSize { get; init; }
}
public class Person
{
public required string Name { get; init; }
public required DateTime Birthday { get; init; }
public required int ShoeSize { get; init; }
}
this way, we can create a new instance like so:
var person = new Person {
Name = "Bobbert",
Birthday = DateTime.Now,
ShoeSize = 42,
};
var person = new Person {
Name = "Bobbert",
Birthday = DateTime.Now,
ShoeSize = 42,
};
proc
procOP4mo ago
Thanks for this - it's this part I couldn't understand what was happening: Name = name; Birthday = birthday; ShoeSize = shoeSize; To me it seemed redundant so I didn't know what the point of this was...
Angius
Angius4mo ago
It's not redundant You set the property value to the value of the parameter Just like, say
public class Counter
{
public int Count { get; } = 0;
public void IncrementBy(int val)
{
Count += val;
}
}
public class Counter
{
public int Count { get; } = 0;
public void IncrementBy(int val)
{
Count += val;
}
}
proc
procOP4mo ago
Your example there makes more sense to me, but this one for example (i think he's called Bro Code on Youtube) he puts this code snippet. So the class part I completely understand what he is doing, and why - but the constructor part, is the brackets after "public Car (" arguments being passed to this constructor? And why does it have to be this.make = make; - etc - that part just seems pointless to me............
class Car
{
String make;
String model;
int year;
String color;

public Car(String make, String model, int year, String color)
{
*this.make = make;
this.model = model;
this.year = year;
this.color = color;*
}
class Car
{
String make;
String model;
int year;
String color;

public Car(String make, String model, int year, String color)
{
*this.make = make;
this.model = model;
this.year = year;
this.color = color;*
}
i put asterisk next to the bit which to me just seems pointless and can't get my head around...... really sorry if this is a stupid question! I get that in future code, you could then put Car car1 = new Car - but why the constructor, what is that doing?
Kouhai
Kouhai4mo ago
A constructor is a special method that gets called when a new instance of the object is created When you have a constructor like Car(String make, String model, int year, String color) you're forcing everyone that attempts to create an instance of the that object to pass these arguments
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.make = make;
this.model = model;
this.year = year;
this.color = color;
These lines are just assigning the class's fields to the arguments passed to the constructor
proc
procOP4mo ago
Nice so immediately that makes sense to me now, just the this.make = make etc - I can't get
Kouhai
Kouhai4mo ago
this.make is refering to String make; that lives in the object
proc
procOP4mo ago
Is "this" part of the C# language - e.g. it's not something the programmer has arbitrarily made up, it's a function or something
Kouhai
Kouhai4mo ago
Yeah, it's a keyword in C# this refers to the current instance of the object You can omit it actually For example
class Car
{
string Make; // Notice how it's capitalized here
public Car(string make)
{
Make = make;
}
}
class Car
{
string Make; // Notice how it's capitalized here
public Car(string make)
{
Make = make;
}
}
Angius
Angius4mo ago
No description
Angius
Angius4mo ago
this in this case is only needed because the name of the field is the same as the name of the parameter
Kouhai
Kouhai4mo ago
Also, why is the tutorial using public fields :sad:
Angius
Angius4mo ago
Usually, field names would be prefixed with _, so private string _make; They're not public tho?
Kouhai
Kouhai4mo ago
Nvm, I'm blind :Kek:
Angius
Angius4mo ago
C# defaults to lowest access when no access modifier is given
Kouhai
Kouhai4mo ago
Yeah ik, idk why I thougth they were public :OMEGALULiguess:
Angius
Angius4mo ago
What I want to question is why it uses System.String instead of string
Kouhai
Kouhai4mo ago
Probably java developer
proc
procOP4mo ago
I really appreciate the feedback and help as I am learning it just feels like something isn't clicking with that - so you said it's assigning the class's fields, to the arguments passed to the constructor ...........let me just churn that through my thick skull for a sec...........
Kouhai
Kouhai4mo ago
The other way around It's assinging the class fields to the values of the passed in arguemnts Not assigning to the actual parameters
proc
procOP4mo ago
Oh wait I think I might get it It's like passing to functions in C where it might be void dothis (int a) - but you could pass it any variable with any name, it's only called a in that function -
Angius
Angius4mo ago
No description
Angius
Angius4mo ago
Yes
proc
procOP4mo ago
Ok the penny might have dropped there
Angius
Angius4mo ago
public class Foo
{
private int _bar;
public Foo(int ungabungaskungamunga)
{
_bar = ungabungaskungamunga;
}
}

var blurbo = 69;
var f = new Foo(blurbo);
public class Foo
{
private int _bar;
public Foo(int ungabungaskungamunga)
{
_bar = ungabungaskungamunga;
}
}

var blurbo = 69;
var f = new Foo(blurbo);
works just fine
proc
procOP4mo ago
Ok ok ok that makes sense........ I really don't know why that just wasn't making any sense at all Probably just because the names were the same on both sides it just looked like what the hell is this code trying to accomplish here Legends , thanks again for this guidance ! o7
Angius
Angius4mo ago
Anytime :Ok:
Want results from more Discord servers?
Add your server