• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Properties in C#

December 24, 2021 C#

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

  • properties (get and set) are members that provide a flexible mechanism for reading, writing or calculating the value of a particular field (in this case an attribute that is private - access modifier);
  • these same allow the data to be easily accessed and also help to promote the security and flexibility of the methods;
  • it is also important to know that properties allow a class to expose a public way of getting and setting value, hiding the implementation or verification code;
  • properties that do not implement a set are read-only.
using System;

namespace Base {
  class Program {
    static void Main(string[] args) {
      var person = new Propriedades();

      person.FirstName = "Nelson";
      person.LastName = "Silva";
      person.Information();
      Console.WriteLine($"Age: {person.age}");

      /*
        Name: Nelson Silva
        Age: 25
      */

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

namespace Base {
  class Properties {
    private string firstName = string.Empty, lastName = string.Empty;
    private int age = 25;
    // public int variable { get; set; }

    public string FirstName {
      set {
        if (value != string.Empty)
          firstName = value;
        else
          Console.WriteLine("The string referring to the first name cannot be empty.");
      }
    }

    public string LastName {
      set {
        if (value != string.Empty)
          lastName = value;
        else
          Console.WriteLine("The string referring to the last name cannot be empty.");
      }
    }

    public int Age { get => age; }

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

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