I am going through the FizzBuzz kata and trying to do it in as much of an object orientated way as possible, just started learning C#.
In that pursuit, I am trying to use a class called, MessageStore
to store various strings and integers to be passed and referenced during runtime without having to hard code as much as possible.
The problem I am having is that I don't think I understand properly how or where to instantiate my class so that is can be called further into the program.
I have tried instantiating at the top of the Program
class with MessageStore returnString
and assigning that instance to variable within Main
, returnString = new MessageStore();
.
I am trying to call the returnString
instance in the first part of the `FizzOrBuzz method, but I can't, not sure of this is down to scope?
The error that is showing, is Cannot access non-static field, 'returnString' in static context
I have tried removing static
from the Main
constructor but that still leaves with with issues.
Any help much appreciated.
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace FizzBuzz
{
class Program
{
// Instantiating MessageStore
MessageStore returnString;
static void Main(string[] args)
{
// Assigning instance a variable name
returnString = new MessageStore();
PlayFizzBuzz(100);
MessageHelper(MessageStore.ReturnCompletedMessage());
Console.ReadLine();
}
public static void PlayFizzBuzz(int startNumber)
{
for (int i = startNumber; i >= 0; i--)
{
if (i == 0)
{
break;
}
MessageHelper(FizzOrBuzz(i));
}
}
public static String FizzOrBuzz(int numberInLoop)
{
if (MultipleCheck(numberInLoop, MessageStore.ReturnThree()) && MultipleCheck(numberInLoop, MessageStore.ReturnFive()))
{
// Trying to call instance with variable name
return returnString.ReturnFizzBuzz();
}
if (MultipleCheck(numberInLoop, MessageStore.ReturnThree()))
{
return MessageStore.ReturnFizz();
}
if (MultipleCheck(numberInLoop, MessageStore.ReturnFive()))
{
return MessageStore.ReturnBuzz();
}
else
return numberInLoop.ToString();
}
public static bool MultipleCheck(int numberToAssess, int multiple)
{
return (numberToAssess % multiple == 0) ? true : false;
}
public static void MessageHelper(string messageText)
{
Console.WriteLine(messageText);
}
class MessageStore
{
public static string ReturnFizz() { return "Fizz!"; }
public static string ReturnBuzz() { return "Buzz!"; }
public static string ReturnFizzBuzz() { return "FizzBuzz!"; }
public static string ReturnCompletedMessage() { return "Looks like we're done here!"; }
public static int ReturnThree() { return 3; }
public static int ReturnFive() { return 5; }
}
}
}