Can someone give me a explanation of a Constructor?
So I was under the impression in order to make a new data type you needed to use a constructor, but I just watched a video that showed that as long as you had the public class variables set up, then you have created the data type. So could someone help explain the difference between these two and the best case uses for doing one over the other or like if you should do one of them since the other is bad scripting.


15 Replies
yes, to instantiate an object you always need to call a constructor
in your first image, there is an implicit default constructor that does nothing (e.g.
var x = new Song();
)
if you never set the value of a class field/property yourself, they will all start with their default values (null or 0)as if I made a constructor and left it empty?
yes, that is the constructor that is automatically being defined since you didn't define one
Is there a difference between doing these? I know the argument in song above is just title, but I changed it to aTitle to see the difference a bit better. I also thought constructors needed to have this.whatever in order to function, but that doesnt seem to be the case
this.title = aTitle;
title = aTitle;
this.
is optional, it's only needed if you have local variables with the same names as your class's fields and need to clarify which one you're referring toinside the context of a constructor or instance method, anyway
if there's no identifier in scope called
aTitle
other than an instance member, it will refer to the instance member
if the reference is ambiguous, then this
is required, E.G.
I see so its probably better practice to do this.whatever just in case wherever its called has another variable of the same name
in theory, yes
in practice, you'll find basically no one does this
naming conventions eliminate the problem
I.E. by naming convention,
private int bar
would be private int _bar
and if there was a public
member on the class, it would be Bar
also, public members should be PascalCase which will always be different from camelCase used for constructor/method arguments
yeah that
😉
different story in VB.NET, where identifiers are not case-sensitive
So in this case, my variable names shouldve all be capitalized?
those would be "properties" not "variables", but yes
well
actually
those would be fields
and should really by convention be
private
oh okay, I thought they had to be public in order for the constructor to work
nope, a constructor is an instance member, and instance members can access all other members of a class
public
is what allows them to be accessed by OTHER classesI appreciate all the advice guys
had to google what init; did. I wanted these to be editable. From what I saw in the documentation it looks like when you do init; it cant be changed. Is that the case or am I miss understanding something?