I can't figure this out. The problem is that the distance, club, cleanclub, hole, scores and par all say inaccessible due to protection level and I don't know why because I thought I did everything right.
namespace homeworkchap8
{
public class Clubs
{
protected string club;
protected string distance;
protected string cleanclub;
protected string scores;
protected string par;
protected string hole;
public string myclub
{
get { return club; }
set {club = value; }
}
public string mydistance
{
get { return distance; }
set { distance = value; }
}
public string mycleanclub
{
get { return cleanclub; }
set { cleanclub = value; }
}
public string myscore
{
get { return scores; }
set { scores = value; }
}
public string parhole
{
get { return par; }
set { par = value; }
}
public string myhole
{
get { return hole; }
set { hole = value;}
}
}
}
this is the derived class:
namespace homeworkchap8
{
public class SteelClubs : Clubs, ISwingClub
{
public void SwingClub()
{
Console.WriteLine("You hit a " + myclub + " " + mydistance);
}
public void clean()
{
if (mycleanclub != "yes")
{
Console.WriteLine("your club is dirty");
}
else
{
Console.WriteLine("your club is clean");
}
}
public void score()
{
Console.WriteLine("you are on hole " + myhole + " and you scored a " +
myscore + " on a par " + parhole);
}
}
}
This is the interface:
namespace homeworkchap8
{
public interface ISwingClub
{
void SwingClub();
void clean();
void score();
}
}
here is the main code:
namespace homeworkchap8
{
class main
{
static void Main(string[] args)
{
SteelClubs myClub = new SteelClubs();
Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();
Console.WriteLine("what club are you going to hit?");
myClub.club = Console.ReadLine();
myClub.SwingClub();
SteelClubs mycleanclub = new SteelClubs();
Console.WriteLine("\nDid you clean your club after?");
mycleanclub.cleanclub = Console.ReadLine();
mycleanclub.clean();
SteelClubs myScoreonHole = new SteelClubs();
Console.WriteLine("\nWhat hole are you on?");
myScoreonHole.hole = Console.ReadLine();
Console.WriteLine("What did you score on the hole?");
myScoreonHole.scores = Console.ReadLine();
Console.WriteLine("What is the par of the hole?");
myScoreonHole.par = Console.ReadLine();
myScoreonHole.score();
Console.ReadKey();
}
}
}
In your base class Clubs the following are declared protected
club;
distance;
cleanclub;
scores;
par;
hole;
which means these can only be accessed by the class itself or any class which derives from Clubs.
In your main code, you try to access these outside of the class itself. eg:
Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();
You have (somewhat correctly) provided public accessors to these variables. eg:
public string mydistance
{
get
{
return distance;
}
set
{
distance = value;
}
}
which means your main code could be changed to
Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();
Dan, it's just you're accessing the protected field instead of properties.
See for example this line in your Main(...):
myClub.distance = Console.ReadLine();
myClub.distance is the protected field, while you wanted to set the property mydistance.
I'm just giving you some hint, I'm not going to correct your code, since this is homework! ;)
myClub.distance = Console.ReadLine();
should be
myClub.mydistance = Console.ReadLine();
use your public properties that you have defined for others as well instead of the protected field members.
In your Main method, you're trying to access, for instance, club (which is protected), when you should be accessing myclub which is the public property that you created.
You organized class interface such that public members begin with "my". Therefore you must use only those members. Instead of
myScoreonHole.hole = Console.ReadLine();
you should write
myScoreonHole.myhole = Console.ReadLine();
It's because you cannot access protected member data through its class instance.
You should correct your code as follows:
namespace homeworkchap8
{
class main
{
static void Main(string[] args)
{
SteelClubs myClub = new SteelClubs();
Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();
Console.WriteLine("what club are you going to hit?");
myClub.myclub = Console.ReadLine();
myClub.SwingClub();
SteelClubs mycleanclub = new SteelClubs();
Console.WriteLine("\nDid you clean your club after?");
mycleanclub.mycleanclub = Console.ReadLine();
mycleanclub.clean();
SteelClubs myScoreonHole = new SteelClubs();
Console.WriteLine("\nWhat hole are you on?");
myScoreonHole.myhole = Console.ReadLine();
Console.WriteLine("What did you score on the hole?");
myScoreonHole.myscore = Console.ReadLine();
Console.WriteLine("What is the par of the hole?");
myScoreonHole.parhole = Console.ReadLine();
myScoreonHole.score();
Console.ReadKey();
}
}
}
You need to use the public properties from Main, and not try to directly change the internal variables.
The reason being you cannot access protected member data through the instance of the class.
Reason why it is not allowed is explained in this blog.
Though it is irrelevant to the case at hand, for the benefit of the next person who arrives at this article through a search engine, if the default constructor of your base class is marked as private, derived classes will incur a CS0122 diagnostic.
Instead, you must promote the private method to protected.
The protected method remains inaccessible to consumers of the derived class unless said class overrides it with a new constructor.
Related
I am trying to make a setter for the public property of the private member age. It operates so that if the age you are trying to input is less than zero, the program should set it to zero and give you a basic message. However, this setter will literally let any negative number slip past it. If you try to edit it in the constructor, the setter doesn't even activate. But if you make an instance of the age class than try to edit that instances class, you can. However, it will let numbers less than zero pass through, and send the message "Viable", meaning it is a viable number. Here is the Person class the age member, property, constructor, etc. is located in.
namespace HopeThisWorks
{
class Person
{
private int age;
public int Age
{
get
{
return age;
}
set
{
if(age >= 0)
{
age = value;
System.Console.WriteLine("Viable");
}
else
{
age = 0;
System.Console.WriteLine("Not Viable");
}
}
}
public Person(int age)
{
this.age = age;
}
}
}
Here is the main method:
using System;
namespace HopeThisWorks
{
class Program
{
static void Main(string[] args)
{
Person p1 = new Person(1);
p1.Age = -1;
}
}
}
Any help would be muchly appreciated. Thank you!
Here's the working thing
using System;
public class Program
{
public static void Main()
{
var p = new Person(-5);
}
}
class Person
{
private int _age;
public int Age
{
get {return _age;}
set
{
if (value >= 0)
{
_age = value;
System.Console.WriteLine("Viable");
}
else
{
_age = 0;
System.Console.WriteLine("Not Viable");
}
}
}
public Person(int age)
{
Age = age;
}
}
In this case result will be Not Viable printed out.
Explanation is in Mark's comment.
using System;
public class Student
{
string name;
int age;
public string inputName()
{
Console.WriteLine("Enter name :");
string name= Console.Readline();
return name;
}
public void showName(string name){
Console.WriteLine(name);
}
static void Main(string[] args)
{
Student myObj = new Student();
string name=myObj.inputName();
myObj.showName(name);
}
}
Unable to understand what is incorrect in the above code. I want to take name and age of student as input through the method in C# class and then print the same using another method. I was thinking I will create an object in main() and call the getters and setters function from main.
Initially, I guessed that the Console.Readline() was causing the issue and therefore tried to look if I was forgetting any library to import for Readline() but could not successfully get the reason behind this reason.
I am totally new to c#, kindly help.
NOTE: I am using an online compiler for my above C# code so if this error is specific to that case kindly let me know that as well.
The main method must not be inside the Student class
public static void Main(string[] args)
{
}
public class Student
{
}
Following errors:
Student myObj = new Student(); // is correct, creates an instance
string name=myObj.inputName(); // semantic error
myObj.showName(name);
Here you declare a new string and assign it the input name function. The inputName() in it of itself is correct, but you probably meant to have the name assigned to the object field string name;
So the following
public string inputName()
{
Console.WriteLine("Enter name :");
string name = Console.Readline();
return name;
}
need to be
public void inputName()
{
Console.WriteLine("Enter name :");
string name = Console.ReadLine();
this.name = name;
}
The return type is changed from string to void, as it does not need to return a value. this.name = name assigns the input to the name field on the object.
The function
public void showName(string name)
{
Console.WriteLine(name);
}
is also a semantic error. There are no functional errors, but you do not need a parameter. The (string name) is the input of the function, if you want to show the current name of the object this is where you use a return type without any parameters.
public string showName()
{
return name;
}
So the final revision would be
public class Program
{
public static void Main(string[] args)
{
Student myObj = new Student();
myObj.inputName();
Console.WriteLine(myObj.showName());
}
public class Student
{
string name;
int age;
public void inputName()
{
Console.WriteLine("Enter name :");
string name = Console.ReadLine();
this.name = name;
}
public string showName()
{
return name;
}
}
}
Newbie here,
So I need to let the user input the length and diameter of the log also I need to use a method for it and use that method in a different class. I think I got the user input part right, but when I try to use the method it tells me that "The name 'Take' does not exist in the current context". How do I fix this?
Using System;
namespace Logger
{
class Loggers
{
private double LogsLength, LogsDiameter; //must be private
public Loggers(double LogsLengthValue, double LogsDiameterValue)
{
LogsLength = LogsLengthValue;
LogsDiameter = LogsDiameterValue;
}
public double TakeLogsLength() { return LogsLength; }
public double TakeLogsDiameter() { return LogsDiameter; }
static void PlaceValues(double LogsLengthValue, double LogsDiameterValue)
{
Loggers r;
r = new Loggers(LogsLengthValue, LogsDiameterValue);
Console.Write("Input the logs length in meters: ");
LogsLengthValue = double.Parse(Console.ReadLine());
Console.Write("\nInput logs diameter in centimeters: ");
LogsDiameterValue = double.Parse(Console.ReadLine());
}
}
class Program
{
static void Main(string[] args)
{
PlaceValues(LogsLengthValue, LogsDiameterValue);
}
}
just a wild guess about what you really wanted to do. But I am not sure.
using System;
namespace ConsoleApp4
{
namespace Logger
{
class Program
{
static void Main(string[] args)
{
UserInput.PlaceValues();
}
}
public class UserInput
{
public static void PlaceValues()
{
Console.Write("Input the logs length in meters: ");
var logsLength = double.Parse(Console.ReadLine());
Console.Write("\nInput logs diameter in centimeters: ");
var logsDiameter = double.Parse(Console.ReadLine());
var loggers = new Loggers(logsLength, logsDiameter);
}
}
public class Loggers
{
private double _logsLength;
private double _logsDiameter; //must be private
public Loggers(double logsLength, double logsDiameter)
{
_logsLength = logsLength;
_logsDiameter = logsDiameter;
}
public double GetLogsLength()
{
return _logsLength;
}
public double GetLogsDiameter()
{
return _logsDiameter;
}
}
}
}
You should make the class and method public to be reachable.
if you want to read more about access modifiers
So your code should look like this:
using System;
namespace Logger
{
public class Loggers
{
private double LogsLength, LogsDiameter; //must be private
public Loggers(double LogsLengthValue, double LogsDiameterValue)
{
LogsLength = LogsLengthValue;
LogsDiameter = LogsDiameterValue;
}
public double TakeLogsLength() { return LogsLength; }
public double TakeLogsDiameter() { return LogsDiameter; }
public static void PlaceValues(double LogsLengthValue, double LogsDiameterValue)
{
Loggers r;
r = new Loggers(LogsLengthValue, LogsDiameterValue);
Console.Write("Input the logs length in meters: ");
LogsLengthValue = double.Parse(Console.ReadLine());
Console.Write("\nInput logs diameter in centimeters: ");
LogsDiameterValue = double.Parse(Console.ReadLine());
}
}
public class Program
{
public static void Main(string[] args)
{
Loggers.PlaceValues(LogsLengthValue, LogsDiameterValue);
}
}
}
I'm currently working on a very simple Pokémon application in C#. I was uncertain on how to set up the relationship between the Pokémon and their fighting type but I just ended up doing the following:
abstract class Pokemon
{
private int number;
private string name;
protected string weakness;
protected string strength;
public Pokemon(int number, string name)
{
this.number = number;
this.name = name;
weakness = "none";
strength = "none";
}
}
I then made seperate classes that inherit Pokemon only to change the specific weakness and strength of the type.
class Fire : Pokemon
{
public Fire(int number, string name) : base(number, name)
{
weakness = "Water";
strength = "Grass";
}
}
Is it bad etiquette to create subclasses with the sole purpose of simply changing some of the initial values of the parent?
From here on, I just intend on doing the following when "creating" Pokémon for the application
pokemon = new Pokemon[6];
pokemon[0] = new Grass(001, "Bulbasaur");
pokemon[1] = new Grass(002, "Ivysaur");
pokemon[2] = new Grass(003, "Venusaur");
pokemon[3] = new Fire(004, "Charmander");
pokemon[4] = new Fire(005, "Charmeleon");
pokemon[5] = new Fire(006, "Charizard");
Any and all advice on how to improve the application or how to use inheritance properly is much appreciated :)
The inheritance looks OK but you may do some improvements. First, you don't need to define protected fields for weakness and strength, use protected properties instead. Second, using string type for weakness/strength doesn't seem to be the best choice. I would go with an Enum type.
enum PokemonComponent {
Water,
Grass
}
abstract class Pokemon
{
private int number;
private string name;
protected Pokemon(int number, string name)
{
this.number = number;
this.name = name;
}
protected abstract PokemonComponent Weakness {
get;
}
protected abstract PokemonComponent Strength {
get;
}
}
class Fire : Pokemon
{
public Fire(int number, string name) : base(number, name)
{
}
protected override PokemonComponent Weakness {
get {
return PokemonComponent.Water;
}
}
protected override PokemonComponent Strength {
get {
return PokemonComponent.Grass;
}
}
}
I am learning C#, i written the below code which is not working.
the protected members can be accessble by inheriting the class, but in the below code it is not working can any one please tell me where i am doing mistake?
class ProtectedDemo
{
protected string name;
public void Print()
{
Console.WriteLine("Name is: {0}", name);
}
}
class Demo : ProtectedDemo
{
static void Main(string[] args)
{
ProtectedDemo p = new ProtectedDemo();
Console.Write("Enter your Name:");
p.name = Console.ReadLine(); //Here i am getting the error.
p.Print();
Console.ReadLine();
}
}
From protected (C# Reference)
The protected keyword is a member access modifier. A protected member
is accessible within its class and by derived class instances.
So from this comment, it is accessible from within ProtectedDemo or from the inheriting class Demo
And then their example
class A
{
protected int x = 123;
}
class B : A
{
static void Main()
{
A a = new A();
B b = new B();
// Error CS1540, because x can only be accessed by
// classes derived from A.
// a.x = 10;
// OK, because this class derives from A.
b.x = 10;
}
}
So change you class to
class Demo : ProtectedDemo
{
static void Main(string[] args)
{
//ProtectedDemo p = new ProtectedDemo();
Demo p = new Demo(); //NOTE HERE
Console.Write("Enter your Name:");
p.name = Console.ReadLine(); //Here i am getting the error.
p.Print();
Console.ReadLine();
}
}
Protected is only accessible for deriving classes or the actual class itself.
Here is an article about access modifiers: What are Access Modifiers in C#?
If you want to set it, either make it public or make a method that takes a string as a parameter and set it there. Something like this.
class ProtectedDemo
{
protected string name;
public void Print()
{
Console.WriteLine("Name is: {0}", name);
}
public void SetName(string newName)
{
name = newName;
}
}
static void Main(string[] args)
{
ProtectedDemo p = new ProtectedDemo();
Console.Write("Enter your Name:");
p.SetName(Console.ReadLine());
p.Print();
Console.ReadLine();
}
or if you want to set it on the Deriving class. Do it like this
class Demo : ProtectedDemo
{
static void Main(string[] args)
{
Demo test = new Demo();
Console.Write("Enter your Name:");
test.name = Console.ReadLine(); // create an instance of the deriving class,
// you can only access the name if you're in the current class created
test.Print();
Console.ReadLine();
}
}
you can only access protected member within the class or with the
object on child class(Demo) which inheriting the parent
class(ProtectedDemo).
you can access it like.
Demo d = new Demo();
d.name = Console.ReadLine();