-4

I am very new to C#. Just started learning about OOP and classes.

I encountered this class in something I read:

public class Thissser
{
    public string whatever;

    public Thissser(string whatever)
    {
        this.whatever = whatever;
    }
}

All that is written in the constructor is this.whatever = whatever;.

What is the point of this and why do you need it?

GSerg
  • 76,472
  • 17
  • 159
  • 346
Mike
  • 1
  • 2
  • Let's say you have the notion of a `Person`. But you say "if you create a person, I need to be 100% sure they have a name". That is why you need a constructor - to _enforce_ the provision of a name (or date of birth, or height, or whatever). There are other reasons, but at an intro level - that is the main reason. So your code takes a `whatever` (think along the lines of "name" in my analogy) parameter in the constructor, then stores it in a field. – mjwills Jul 17 '21 at 14:14
  • The line of code you are referring to is just for setting the member whatever in the constructor. Usually, when code like this is written, it means that when someone instantiates a Thissser class, he/she needs to pass in some sort of whatever. – tomerpacific Jul 17 '21 at 14:14
  • 1
    I added a few links for you to take a look at. The first thing you should learn is how to do research, if you want to ever be a good developer. There's thousands of books/articles/videos/etc about OOP – Camilo Terevinto Jul 17 '21 at 14:18

2 Answers2

0

It sets the public string whatever to whatever string whatever is. It would be easier to understand with different names

public class Thissser
{
  public string instance_whatever;

  public Thissser(string incoming_whatever)
  {
    this.instance_whatever = incoming_whatever;
  }
}

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
-2

We use constructors to initialize the object with the default or initial state. The default values for primitives may not be what are you looking for. Another reason to use constructor is that it informs about dependencies.

For more details refer: Javatpoint

OpOp_1
  • 59
  • 8