Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Evan Welch
Evan Welch
1,815 Points

Why is "base" necessary?

Why must we used "base"?

Would it be equivalent to "Point(x,y)" since this is the parent class to the MapLocation class?

Thank you in advance!

2 Answers

Simon Coates
Simon Coates
8,223 Points

You comment doesn't seem to be linked to any content, so I don't know precisely what context this is from. The class name is something you'd use in a static context. If you want to call a method on the parent, I think you can just call it. However, if there is a method with the same signature on the subclass, then you might need the base keyword. It's been a while since i did c#, but i tried to create a quick demo. (The following is the code and the output I generated in https://repl.it/languages/csharp )

class Super {
    public virtual void output()
    {
      System.Console.WriteLine("super");
    }
    public void otherout()
    {
      System.Console.WriteLine("otherout");
    }
}
class Sub : Super {
    public override void output()
    {
      System.Console.WriteLine("sub");
    }
    public void other()
    {
      output();
      base.output();
      otherout();
      //Super.otherout();//produces an Error
    }
}
using System;

class MainClass {
  public static void Main (string[] args) {
    var x = new Sub();
    x.other();
  }
}

/*
output is:
sub
super
otherout
*/

It demos that base seems to allow you to hit the subclass method and the superclass method.

Evan Welch
Evan Welch
1,815 Points

Terribly sorry about leaving out the context. I didn't realize there were multiple ways to use "base." And thank you for the well written answer.

File MapLocation

namespace SameNamespace
{
  class MapLocation : Point(x, y)
  {
      public MapLocation(int x, int y) : base(x, y)
      {
      }
  }
}

I learned that "base is referring to the Point parent class to the constructor MapLocation. Thank you again for taking the time to help me learn this.