0

Is there a way to store the return of a method in a class variable outside of the class but the return of the class is a class itself. I know that was confusing, so I put my code below.

namespace MagicalInheritance
{
  class Pupil{
    public string Title{get; private set;}

    public Pupil(string title){
      Title = title;
    }

    public Storm CastWindStorm(){
      Storm storm = new Storm("wind", false, Title);
      return storm;
    }
  }
}

This is where I am trying to store the return:

namespace MagicalInheritance
{
  class Program
  {
    static void Main(string[] args)
    {
      Storm sto = new Storm("wind", false, "Zul'rajas");
      Pupil pup = new Pupil("Mezil-kree");
      Storm storm = Pupil.CastWindStorm();

      Console.WriteLine(sto.Announce());
      Console.WriteLine(storm.Announce());
    }
  }
}

These are the errors that I get when I try to run the code.

Program.cs(11,13): error CS8171: Cannot initialize a by-value variable with a reference [/home/ccuser/workspace/learn-csharp-interfaces-inheritance-csharp-supernatural-inheritance/MagicalInheritance.csproj]

Program.cs(11,25): error CS0120: An object reference is required for the non-static field, method, or property 'Pupil.CastWindStorm()' [/home/ccuser/workspace/learn-csharp-interfaces-inheritance-csharp-supernatural-inheritance/MagicalInheritance.csproj]

A Name
  • 27
  • 4
  • You haven't shown us the `Storm` class, which doesn't help - but the `Pupil.CastWindStorm()` call should be `pup.CastWindStorm()`, because you're trying to call a method on the newly-created `Pupil` instance. – Jon Skeet Dec 13 '20 at 19:34

1 Answers1

2

The code

Storm storm = Pupil.CastWindStorm();

will only work if CastWindStorm() is declared static.

To correct the problem, use the object reference instead:

Storm storm = pup.CastWindStorm();
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501