• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Constructors in C#

December 21, 2021 C#

In this post, you will learn how to work with constructors so that you can use that same knowledge and thus evolve.

  • the constructors have as function to initialize everything that is necessary when creating a certain object;
  • you can create several constructors in a class.
using System;

namespace Base {
  class Program {
    static void Main(string[] args) {
      var person1 = new Constructors("Nelson", "Silva", 25);
      var person2 = new Constructors("Larissa", "Fernandes", 17);

      person1.Information();
      person1.CheckEntrance();

      /*
        Name: Nelson Silva
        Age: 25
        This person can enter the site because he is over 18 years old.
      */

      person2.Information();
      person2.CheckEntrance();

      /*
        Name: Larissa Fernandes
        Age: 17
        This person cannot enter the site because he is under 18 years of age.
      */

      Console.ReadKey();
    }
  }
}
using System;

namespace Base {
  class Constructors {
    string firstName = string.Empty, lastName = string.Empty;
    int age = 0;

    public Constructors(string firstName, string lastName, int age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
    }

    public void Information() {
      Console.WriteLine($"Name: {firstName} {lastName}");
      Console.WriteLine($"Age: {age}");
    }

    public void CheckEntrance() {
      if (age >= 18)
        Console.WriteLine("This person can enter the site because he is over 18 years old.");
      else
        Console.WriteLine("This person cannot enter the site because he is under 18 years of age.");
    }
  }
}

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved