C# How do I use a method in a different class - c#

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);
}
}
}

Related

Method doesn't set value of an object

I'm new to C# and have no idea why doesn't it work. I'm trying to create 3 methods that create a new Vehicle object with different properties. I've tried to do it with polymorphism but it's been even worse. I bet the answer to that is so easy..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace PetrolStation
{
class Program
{
static void Main(string[] args)
{
Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
aTimer.Interval = 1000; // 1000=1s
aTimer.Enabled = true;
Console.ReadLine();
void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
Random rand = new Random();
int temp = rand.Next(1, 3);
if (temp == 2)
{
Vehicles vehicle = new Vehicles();
vehicle.newCar();
Console.Out.WriteLine("test", vehicle.carType); // it should print "car" after test but it doesn't
}
if (temp == 3)
{
Vehicles vehicle = new Vehicles();
vehicle.newVan();
Console.Out.WriteLine("test", vehicle.carType);// it should print "van" after test but it doesn't
}
}
}
}
Second class:
public class Vehicles
{
public string carType;
public string fuelType;
public int tankCap;
public double fuelInTank;
public Random rand = new Random();
public void newCar()
{
carType = "Car";
tankCap = 40;
fuelInTank = rand.NextDouble() * 10;
int tempFuelType = rand.Next(1, 3);
switch (tempFuelType)
{
case 1:
fuelType = "petrol";
break;
case 2:
fuelType = "Diesel";
break;
case 3:
fuelType = "LPG";
break;
}
}
public void newVan()
{
carType = "van";
tankCap = 80;
fuelInTank = rand.NextDouble() * 20;
int tempFuelType = rand.Next(1, 2);
if (tempFuelType == 1)
{
fuelType = "Diesel";
}
else
{
fuelType = "LPG";
}
}
using System;
namespace StackOverflow_OOP
{
class Program
{
// Randomness removed: you want a driver to **consistently** pass or fail.
static void Main(string[] args)
{
Car car = new Car(VehicleFuelType.Petrol, 20);
// The first arg specifies format/placement of the second
Console.Out.WriteLine("Vehicle Type: {0}", car.Type);
// In background, uses String.Format()
// See https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx
Van van = new Van(VehicleFuelType.Diesel, 40);
Console.Out.WriteLine("Vehicle Type: {0}", van.Type);
Console.ReadLine();
}
}
// A string that only takes a small number of values is called an enumeration
// See https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
public enum VehicleFuelType
{
Petrol,
Diesel,
LPG
}
// Vehicle is clearly abstract in this context, while Car & Van are concrete.
// See explaination after code.
public abstract class Vehicle
{
public VehicleFuelType FuelType { get; }
public int TankCap { get; }
public double FuelInTank { get; private set; }
public string Type { get { return this.GetType().Name; } }
public Vehicle(VehicleFuelType fuelType, int tankCap, double fuelInTank)
{
FuelType = fuelType;
TankCap = tankCap;
FuelInTank = fuelInTank;
}
}
public class Car : Vehicle
{
public Car(VehicleFuelType fuelType, double fuelInTank) : base(fuelType, 40, fuelInTank)
{
}
}
public class Van : Vehicle
{
public Van(VehicleFuelType fuelType, double fuelInTank) : base(fuelType, 80, fuelInTank)
{
}
}
}
Classes: Abstract vs. Concrete
public abstract class Shape
{
public abstract double GetArea();
}
public class Circle : Shape
{
public int Radius { get; }
public Circle(int radius)
{
Radius = radius;
}
public override double GetArea()
{
return Math.PI * Radius * Radius;
}
}
public class Square : Shape
{
public int SideLength { get; }
public Square(int sideLength)
{
SideLength = sideLength;
}
public override double GetArea()
{
return SideLength * SideLength;
}
}
The simplest difference between an abstract class and a concrete one:
An abstract class cannot be instantiated (directly); a concrete one can.
For instance,
Shape shape = new Shape(); // impossible
Circle circle = new Circle(); // fine
Crucially,
Shape circle = new Circle(); // fine
Conceptually, it's impossible to create an abstract class (e.g. shape) without actually creating a concrete class (circle).
Even more simply, imagine going to a restaurant and telling the waiter you want "food". Obviously he can comply, but somewhere along the line "food" must become steak or tuna or spaghetti, etc.
Regarding the direct problem you mentioned:
The problem is related to the WriteLine call.
The signature of the call you mane
Console.Out.WriteLine("test", vehicle.carType);
is
public virtual void WriteLine(string format, object arg0)
So the first parameter in this call should have an item which you want to composite (see https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx for more details).
bottom line the call should be something like
Console.Out.WriteLine("test {0}", vehicle.carType);
Regarding the "polymorphism" you mentioned:
What you implemented isn't polymorphism.
You might want to read about polymorphism a little bit:
oop: https://msdn.microsoft.com/en-us/library/mt656686.aspx
polymorphism: https://msdn.microsoft.com/en-us/library/ms173152.aspx

data structure of objects and methods in c#

I am new to c# and fairly new to programming. I need help with a topic which i have been trying to figure out from the past week. I have 3 files:
Control: this is an interface and should contain the list of my
methods
ControlImpl : this the implementaion of the interfaces.
Runtime: contains which the binding code between the main method
and the interface implementaion
Test_main: from where i call the
runtime method 'call'
Problem: there can be any number of instances(for ex: c, c1, c2, etc) in Control file and each instance should be able to call SetTime() and Nop() methods.
I made a list of the methods SetTime() and Nop(). But how can i add the instance to a list so that each instance when called should call its methods?
CONTROL
namespace create_interface
{
interface Control
{
void SetTime(params object[] paramsArr);
void Nop(params object[] paramsArr);
}
public class CM
{
Control c = new ControlImpl();
public List<object> ControlMain()
{
List<object> methods = new List<object>();
methods.Add(new Action<object[]>(c.SetTime));
methods.Add(new Action<object[]>(c.Nop));
return methods;
}
}
}
ControlImpl :
namespace create_interface
{
public class ControlImpl : Control
{
void Control.SetTime(params object[] paramsArr)
{
Console.WriteLine("inside Control.SetTime {0} ", paramsArr[0]);
}
void Control.Nop(params object[] paramsArr)
{
Console.WriteLine("inside Control.Nop ");
}
}
}
Runtime:
namespace create_interface
{
public class runtime
{
public void call(params object[] methodparams)
{
if ((methodparams[0].Equals(0)) || (methodparams[0].Equals(1)))
{
//List<Control> objectlists = cmObject.ControlObjectList();
List<object> methods = cmObject.ControlMain();
//Console.WriteLine(methods.Count);
Action<object[]> method = (Action<object[]>)methods[(int)methodparams[0]]; //object[]
object[] args = new object[] { methodparams[1] };
method(args);
}
else
Console.WriteLine("wrong ID number entered");
}
Test_main:
namespace create_interface
{
class test_main
{
static void Main(string[] args)
{
long time;
CallingFunc CF = new CallingFunc();
Console.WriteLine("enter method ID");
int methodID = Convert.ToInt32(Console.ReadLine());
try
{
switch (methodID)
{
case 0:
Console.WriteLine("enter the time in long");
time = Convert.ToInt64(Console.ReadLine());
CF.call(methodID, time);
break;
case 1:
CF.call(methodID, null);
break;
default:
Console.WriteLine("you entered wrong method ID or parameters");
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Please take a look at the following solution and we can use it as a base to come up with your final solution:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace StackOverflow38200633
{
class Program
{
static void Main(string[] args)
{
Collection<IControl> controls = new Collection<IControl>();
controls.Add(ControlFactory.Create());
controls.Add(ControlFactory.Create());
controls.Add(ControlFactory.Create());
ControlManager manager = new ControlManager(controls);
Console.WriteLine("Enter method ID:");
int methodID = Convert.ToInt32(Console.ReadLine());
try
{
switch(methodID)
{
case 0:
Console.WriteLine("Enter the time in long: ");
long time = Convert.ToInt64(Console.ReadLine());
manager.InvokeAllSetTime(time);
break;
case 1:
manager.InvokeAllNop();
break;
default:
Console.WriteLine("You entered wrong method ID or parameters");
break;
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public interface IControl
{
void SetTime(long time);
void Nop();
}
public class ConcreteControl : IControl
{
public void SetTime(long time)
{
Console.WriteLine("inside Control.SetTime {0} ", time);
}
public void Nop()
{
Console.WriteLine("inside Control.Nop ");
}
}
public class ControlManager
{
public void InvokeAllSetTime(long time)
{
foreach(IControl control in _controls) control.SetTime(time);
}
public void InvokeAllNop()
{
foreach(IControl control in _controls) control.Nop();
}
public ControlManager(Collection<IControl> controls)
{
_controls = controls;
}
public Collection<IControl> _controls { get; private set; }
}
public static class ControlFactory
{
public static IControl Create()
{
return new ConcreteControl();
}
}
}

Trouble with assigning/calling methods from another class C#

I've looked through other questions but I can't understand what's going on in the answer so I'll post my code here:
public class Program
{
public static void Main()
{
Program startUp = new Program();
Console.Clear();
string file = #FILEPATH
string grades = File.ReadAllText(file);
int acount = grades.Count(c => c == 'A');
startUp.Grapher();
}
public class Graph
{
public static string Grapher(int acount)
{
Console.WriteLine(String.Concat(Enumerable.Repeat("*", acount))); Console.Write(": A");
}}
Any help or explanation would be fantastic!
ok, from what i see you create a Program class instance and then try to use a Graph class method.
you should use Graph class instance.
public static void Main()
{
Console.Clear();
string file = #FILEPATH
string grades = File.ReadAllText(file);
int acount = grades.Count(c => c == 'A');
Graph.Grapher(acount);// this is the change
}
and the Graph class will be:
public class Graph
{
public static void Grapher(int acount)// the change is here
{
Console.WriteLine(String.Concat(Enumerable.Repeat("*", acount))); Console.Write(": A");
}
}

is inaccessible due to its protection level

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.

Create a class in C# such that it can't be instantiated and satisfy following conditions :

Create public class in C# such that following conditions are satisfied :
The class cannot be instantiated.
A function from that class can be called by other class.
I tried this way :
public abstract class A {
public static void fun()
{
// do process.
}
}
public class B : A
{
// Now A can't be instantiated being abstract.
// And you can call its function like this :
A.fun();
}
But my answer was wrong.So, please help me out.
You can create a class like as follows to meet your goal
public class A
{
private A()
{
}
public static A GetA()
{
return new A();
}
public void Foo()
{}
}
public class B
{
public void Foo2()
{
A a = A.GetA();
a.Foo();
}
}
Making the constructor of A private would bar it from instantiating from another class. And the static method GetA will return an object of A instatiating it privately which you can use from any class.
you can use static class if you don't like allow to instantiate it use static class, The best sample for it is Math class, Also if you want to have a single instance you can use singleton.
MSDN sample:
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9 / 5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}
And for creating class singleton do this:
public sealed class MyClass
{
MyClass()
{
}
public static MyClass Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly MyClass instance = new MyClass();
}
}

Categories