Classes in C#

Continuing with this idea of learning C#, I am going to look at how each language handles a simple class. I’ll just make a class Person with a few properties/attributes and a method to describe the person.

As usual, I’ll start it out in Ruby. One thing that has stuck with me from a great teacher at Turing, Abdul, is to only use attr_accessor when absolutely necessary, so I will use attr_reader here.

class Person
  attr_reader :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def person_info
    puts "#{@name} is #{@age} years old."
  end
end

person = Person.new("John Doe", 30) 
person.person_info

Above, we have the class, an attr_reader to allow the attributes of the class to be read outside of the class, initialize to build the class when you create a new instance with new, attributes (@name and @age), and a method (defined with def) that outputs a simple string with the name and age interpolated inside of it.

To do the same thing in C#, the setup is a little bit different. You need to make sure it is using System, and then define the public class. Next you can describe the properties (don’t forget to acknowledge the data type), and then build the person. The properties are defined with get and set to encapsulate the fields in the class.

To create a new instance, you’re going to use a method with the same name as the class, but you will still use new. Instead of using something like puts you are going to use Console.WriteLine to print it to the console. The string interpolation also looks slightly different.

using System;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void PersonInfo()
    {
        Console.WriteLine($"{Name} is {Age} years old.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person("John Doe", 30);
        person.PersonInfo();
    }
}

Hopefully that is helpful, as always, let me know if you have any questions/corrections for me


Comments

Leave a Reply

Discover more from Brendan Bondurant

Subscribe now to keep reading and get access to the full archive.

Continue reading