I’m trying to create a program which has multiple classes. In the program.cs I have inserted example text but whenever I run the program it doesn’t output the text it only outputs the name of the program and the class files, e.g. Testprogram.Customer
And I can’t workout why.
The Bank code is:
namespace CashMachine
{
class Bank
{
private string bankname;
private string location;
public Bank(string name, string location)
{
this.bankname = bankname;
this.location = location;
}
public string Getname()
{
return this.bankname;
}
public string Getlocation()
{
return this.location;
}
}
}
The program cs code is:
namespace CashMachine
{
class Program
{
static void Main(string[] args)
{
Bank b = new Bank("NatWest", "London");
{
Console.WriteLine(b);
}
Console.WriteLine();
Console.WriteLine();
Customer c = new Customer("Joe", "UK", "joelndn", "May");
Console.WriteLine(c);
Console.ReadKey();
}
}
}
If we take the first example, of Bank, you have:
Bank b = new Bank("NatWest", "London");
Console.WriteLine(b);
Now; the system doesn't automatically know what you want to write about the Bank, but everything that subclasses object has a public virtual string ToString() method, for creating a text representation of a type, so: this is what gets called. The default implementation of ToString() is to output the type name, but if you want to do something more interesting: tell it what you want.
I would suggest:
public override string ToString()
{
return Getname();
}
You can do something similar with Customer to tell it what the default output would be for that.
Alternatively: just be explicit in your output code, i.e.
Console.WriteLine(b.Getname());
Finally, you might want to consider properties instead of methods like Getname, for example (using modern C# syntax):
class Bank
{
public string Name { get; }
public string Location { get; }
public Bank(string name, string location)
{
Name = name;
Location = location;
}
public override string ToString() => Name;
}
Related
I am trying to print two methods that i have created but i cant figure out how to do it.
My project consists of Language.cs file in addition to Program.cs
This method in Language.cs:
public static void PrettyPrintAll(IEnumerable<Language> langs)
{
foreach (var printsAll in langs)
{
Console.WriteLine(printsAll.Prettify());
}
}
Prints out this method that is also in Language.cs:
public string Prettify()
{
return $"{Year}, {Name}, {ChiefDeveloper}, {Predecessors}";
}
this method prints out every query result (is also in Language.cs):
public static void PrintAll(IEnumerable<Object> sequence)
{
foreach (var prints in sequence)
{
Console.WriteLine(prints);
}
}
Language class code other than the methods above:
namespace ProgrammingLanguages
{
public class Language
{
public static Language FromTsv(string tsvLine)
{
string[] values = tsvLine.Split('\t');
Language lang = new Language(
Convert.ToInt32(values[0]),
Convert.ToString(values[1]),
Convert.ToString(values[2]),
Convert.ToString(values[3]));
return lang;
}
public int Year
{ get; set; }
public string Name
{ get; set; }
public string ChiefDeveloper
{ get; set; }
public string Predecessors
{ get; set; }
public Language(int year, string name, string chiefDeveloper, string predecessors)
{
Year = year;
Name = name;
ChiefDeveloper = chiefDeveloper;
Predecessors = predecessors;
}
All the methods are within the Language.cs file.
My issue is that i do not understand how to print them, i have tried in many ways but always get an error code The name 'PrintAll' does not exist in the current context or something like that.
In main this is how i have tried to call the method PrintAll:
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year}
{languagePrint.Name} {languagePrint.ChiefDeveloper}");
PrintAll(stringLanguage);
The static method PrintAll() belongs to the class Language and calling it from another class requier to prepend the class name first, such as Language.PrintAll()
public static void Main()
{
// some code ...
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year} {languagePrint.Name} {languagePrint.ChiefDeveloper}");
// PrintAll(stringLanguage); <-- This won't work because there is no method PrintAll() in the current class
// This now refers to the correct class where the method belongs
Language.PrintAll(stringLanguage);
}
Another way to do that would be to include the static part of the class Language in the class where Main is (I assume the class Program) :
// replace namespace by the correct namespace of the class
using static namespace.Language;
class Program
{
public static void Main()
{
// some code ...
var stringLanguage = languages.Select(languagePrint => $"{languagePrint.Year} {languagePrint.Name} {languagePrint.ChiefDeveloper}");
// This now works because the static parts were imported
PrintAll(stringLanguage);
}
}
However, I discourage using this, because this may lead to confusion
Here is my problem:
I want to output a value from a class when I call to its instance.
For example, I have a class like this:
class Car
{
public string name = null;
public int id;
public int horsepower;
public Car(int ID, string Name, int HorsePower)
{
this.id = ID;
this.name = Name;
this.horsepower = HorsePower;
}
}
I want the output will be "aventador lp700-4" when I have a program like this:
class Program
{
static void Main(string[] args)
{
Car car = new Car(1, "aventador lp700-4", 700);
////////////// I want the output will be "aventador lp700-4" /////////////////////
Console.WriteLine(car);
///////////////////////////////
Console.Read();
}
}
I find some dll library could do that, but I don't know how to to.
Console.WriteLine(object) wants to get a string for the object passed in; there are a few different ways it can do that, but the default (in the absence of you telling it something more specific) is that it is just going to call .ToString() on the argument. So: you need to override the ToString() method on Car, to tell it what you want to use to represent that type as a string:
class Car
{
// ... your existing code
public override string ToString() { return name; }
}
Override the ToString method in your car class
public override string ToString(){
return name;
}
Relatively minor question about something I am missing here,
I am attempting to do a simple GetSet in C# to get the hang of the syntax but appear to have missed something as all that is printed is GetSet.Role and not the actual attributes being assigned.
Have I just worded something wrong? Apologies for the minor question but any help is appreciated.
namespace GetSet
{
class Program
{
static void Main(string[] args)
{
Role Mage = new Role("Staff", "Robes", "Magic affinity");
Role Warrior = new Role("Sword", "Platebody", "Strength");
Role Rogue = new Role("Needle", "Leather", "Cunning");
Console.WriteLine(Mage);
Console.WriteLine(Warrior);
Console.WriteLine(Rogue);
//stop the program from closing
Console.ReadLine();
}
}
}
and the following is my class:
namespace GetSet
{
class Role
{
//private variables
private string weapon;
private string armour;
private string passive;
//public structs
public Role(string aWeapon, string aArmour, string aPassive)
{
weapon = aWeapon;
armour = aArmour;
passive = aPassive;
}
//Getters and Setters for above private variables
public string Weapon
{
get { return weapon; }
set { weapon = value;}
}
public string Armour
{
get { return armour; }
set { armour = value;}
}
public string Passive
{
get { return passive; }
set { passive = value;}
}
}
}
Add a ToString() to your Role class and set it return whatever you want:
public override string ToString()
{
return $"Weapon: {weapon}, Armor: {armor}, Passive: {passive}";
}
You need to override the ToString method on the GetSet class.
Something like:
public override string ToString()
{
return $"{weapon}/{armour}/{passive}";
}
Update
You can simplyfy your Role class.
internal class Role
{
public Role(string weapon, string armour, string passive)
{
Weapon = weapon;
Armour = armour;
Passive = passive;
}
public string Weapon { get; }
public string Armour { get; }
public string Passive { get; }
public override string ToString()
{
return $"{Weapon}/{Armour}/{Passive}";
}
}
Re: vasily.sib's comment.
If you need to change the properties after object creation then simply change
public string Passive { get; }
to
public string Passive { get; set; }
As other answers lacks of getters/setters syntax examples, I will post my.
namespace GetSet
{
public class Role
{
// private backing field
private string _weapon;
// properties can have getters and setters, that contains some logic
public string Weapon
{
get { return _weapon; }
set { if (_weapon != vale) _weapon = value; }
}
// there is an auto-getters/setters
// in this case, backing field is handled by .Net CLR
public string Armour { get; set; }
// getters and setters may have different access level
// also, note property initializer '= "John";' - this will set property value
// to "John" right before constructor invocation
public string Name { get; private set; } = "John";
// properties also can be readonly, so they can be setted only in constructors
public string Passive { get; }
// public constructor
public Role(string passive)
{
Passive = passive;
}
public void ChangeName(string newName)
{
Name = newName; // setting property through private setter
}
// I believe, that this method shouldn't be used to represent object as string
// At least, I think, you should never relay on it's return value, BUT it ups to you
public overide string ToString() => Name;
}
}
Also, as you can see, I'm not setting publicly available properties (properties with public setters, Weapon and Armour) in consturctors, because I can initialize them along with constructing Role object, like this:
var mage = new Role("Magic affinity") { Weapon = "Staff", Armor = "Robes" };
mage.ChangeName("John, Doe");
As said before, I beleive that it is not relay on object itself, how it will look in string. I thinking so, because if you for some reasons need to represent same object as different strings in different places of your code - this will cause troubles. So instead of this:
// this will call .ToString() method
Console.WriteLine(mage);
// output: John, Doe
I suggest this:
// represent object as you need
Console.WriteLine($"{mage.Name} - walks in {mage.Armour}, beats with {mage.Weapon}");
// output: John, Doe - walks in Robes, beats with Staff
I am trying to store data into a complex type list and then print it later. I am trying to use properties and then print it but it seems like I am missing something. Please help.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Color");
string color = Console.ReadLine();
Console.WriteLine("Enter transmition");
string transmition = Console.ReadLine();
Console.WriteLine("Enter Name");
string name = Console.ReadLine();
List<DatabaseCar> arr = new List<DatabaseCar> { };
DatabaseCar databaseCar = new DatabaseCar(color, transmition, name);
arr.Add(databaseCar);
foreach (DatabaseCar data in arr)
{
Console.WriteLine(data);
}
Console.ReadKey();
}
}
abstract class Data
{
protected string color;
protected string engine;
protected string name;
public abstract void set(string color, string engine, string name);
public string Color
{
get
{
return color;
}
}
public string Engine
{
get
{
return engine;
}
}
public string Name
{
get
{
return name;
}
}
}
class DatabaseCar : Data
{
public override void set(string color, string engine, string name)
{
this.color = color;
this.engine = engine;
this.name = name;
}
public DatabaseCar(string color, string engine, string name)
{
set(color, engine, name);
}
}
The result I get from it is:
Enter Color:
Red
Enter transmition:
Manual
Enter Name:
John
ConsoleApp1.DatabaseCar
This is because Console.WriteLine calls ToString() on an object that isn't specifically supported by one of its other overloads. ToString() by default returns the string representation of the Type.
To address this, you'll have to override ToString() with a custom implementation that does what you want.
public override string ToString()
{
// construct the representation that you want and return it.
}
Your problem is in the way you print your data.
foreach (DatabaseCar data in arr)
{
Console.WriteLine(data);
}
data is an instance of the type DatabaseCar, which is a class defined by you. It contains many different properties of different types. So you need to tell C# how to print it.
There's two ways to go about it. One, a dedicated method to print an object of type DatabaseCar. You can customize how the print is done, this is a very basic example.
static void PrintDatabaseCar(DatabaseCar car)
{
Console.WriteLine("Name : {0}", car.Name);
Console.WriteLine("Color : {0}", car.Color);
Console.WriteLine();
}
Then you can call that method from your main like so:
foreach (DatabaseCar data in arr)
{
PrintDatabaseCar(data);
}
Option two, you can override the ToString() method and provide functionality to print an object of type DatabasCar. This method has to go in your DatabaseCar class definition.
class DatabaseCar : Data
{
public override void set(string color, string engine, string name)
{
this.color = color;
this.engine = engine;
this.name = name;
}
public DatabaseCar(string color, string engine, string name)
{
set(color, engine, name);
}
public override string ToString()
{
string result = string.Empty;
result += string.Format("Name : {0}", name) + Environment.NewLine;
result += string.Format("Color : {0}", color) + Environment.NewLine;
result += Environment.NewLine;
return result;
}
}
Got it.
Thanks Everyone
public override string ToString()
{
// construct the representation that you want and return it.
return String.Format("Color {0},Engine {1}, Name {2}",color,engine,name);
}
public class Program
{
public static void Main(string[] args)
{
var c = check.myValue("Example 1"); //This is the pattern I've to use, don't want to create an object (Is it possible to use it with static class)
Console.WriteLine(c.result1);
Console.WriteLine(c.result2);
}
}
public static class check
{
public static void myValue(string qr)
{
public string result1 = "My Name" + qr;
public string result1 = "You're" + qr;
}
}
See here Online Example (Code is not working)
Every thing on main function I've to use exactly the same pattern because I'll use it in a lot of different classes and I don't want to create object each and every time by using non-static class.
Please correct me if I'm wrong
There's a lot wrong with the syntax of that code, which #Sergey addresses in his answer.
You appear to want to return an instance of a class from a static method, and that class should contain two properties.
You can do that by creating the actual, nonstatic class containing the properties:
public class Check
{
public string Result1 { get; set; }
public string Result2 { get; set; }
}
Then return a new instance from the static method therein:
public static Check MyValue(string qr)
{
var result = new Check();
result.Result1 = "My Name" + qr;
result.Result2 = "You're" + qr;
return result;
}
However, you're saying in the comments in your code that you don't want to use an object.
In that case it appears you want to use static properties. That's generally not recommendable, but it would look like this:
public static class Check
{
public static string Result1 { get; set; }
public static string Result2 { get; set; }
public static void MyValue(string qr)
{
Result1 = "My Name" + qr;
Result2 = "You're" + qr;
}
}
Then you can read Check.Result1 after calling the method MyValue().
Your code is totally wrong
myValue method returns void. You cannot assign void return value to variable.
You cannot have public modifiers for local variables.
You cannot have local variables with same name in same scope
If you want to return two values from method, then you should return object with two fields - custom class or tuple. You can also use out parameters, but I don't think it's your case
public static class Check
{
public static Tuple<string, string> MyValue(string qr)
{
return Tuple.Create($"My Name {qr}", $"You're {qr}");
}
}
With C# 7 it's a little bit better. You can write this method in one line and provide names for tuple properties
(string MyName, string YourName) MyValue(string qr) => ($"My Name {qr}", $"You're {qr}");
Usage
var result = Check.MyValue("Example 1");
Console.WriteLine(result.Item1); // result.MyName
Console.WriteLine(result.Item2); // result.YourName
You can practice with creating custom class with nicely named properties instead of using tuples.