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;
}
Related
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;
}
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.
I am trying to use a method to create an object and return that object to main(). Once in main I want to be able to access the properties of that object such as print Holly.age. VS does not recognize the object Holly in main() to have any properties. Is anyone able to tell what I am doing wrong or let me know if it's not something possible in c#.
Thanks in advance to anyone who gives there time to help.
class program
{
static void Main(string[] args)
{
object Holly = createobject(Holly, 21);
int hollyage = Holly.age; // This Line is the problem Holly.age is not recognized
// as anything
}
public static object createobject(string name, int i)
{
Cat Holly = new Cat(name, i);
return Holly;
}
public class Cat
{
public string name;
public int age;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public Cat(string name, int age)
{
this.name = name;
this.age = age;
}
}
VS does not recognize the object Holly in main() to have any properties
This is because you have declared Holly to be object rather than Cat, and similarly your create routine returns object rather than Cat.
To be able to use any of the properties of Cat you need to cast Holly back to Cat or better still, return Cat from your create routine. Unless you intend to extend your create routine to do more, you don't really need it and can simply do:
Cat Holly = new Cat("Holly", 21);
You also have both public fields and public properties in your Cat class. The fields should be made private, but that's not the cause of the problem.
Your method createobject returns an object. So you must first cast it back into Cat before you can access Age:
int hollyage = ((Cat)Holly).Age;
In addition your call to the createobject is wrong. It requests a string. Change to:
createobject("Holly", 21);
The correct way to write your code would be:
static void Main(string[] args)
{
//variable name in camelCase.
//"Holly" is a string
object holly = CreateObject("Holly", 21);
//Casting from object to Cat so you can access Age property
int hollyAge = ((Cat)holly).Age;
}
//Function names EachWorkCapitalized
public static object CreateObject(string name, int i)
{
Cat holly = new Cat(name, i);
return holly;
}
public class Cat
{
//If you implement your properties with the default get set behavior
//better use automatically implemented properties
public string Name { get; set; }
public int Age { get; set; }
public Cat(string name, int age)
{
Name = name;
Age = age;
}
}
You don't actually need public static object createobject()
You can simply remove that and change your Main to:
static void Main(string[] args)
{
Cat Holly = new Cat("Holly", 21);
int hollyage = Holly.age;
}
The problem is that Holly is defined as an object class, and object classes do not have an age or Age property.
You should change the line as:
Cat Holly = createObject("Holly", 21) as Cat;
Then the intellisense will recognize the Holly variable as being of type Cat.
You could always cast the object to the correct type to access it's members.
int hollyage = ((Cat)Holly).Age;
I'm having trouble writing up some code. I'm not too sure where and how to write up the constructors and the accessors.
The activity I have to do is this:
Write 3 derived classes to allow a user to enter the details of three types of Vehicles with their attributes.
• Car (make, model, year, bodyType)
• Airplane (make, model, year, noEngines, engineType)
• Boat (make, model, year, length, hullType)
The 4th class is the base class Vehicle which contains the shared attributes and methods
Make all attributes either private (in derived classes) or protected (in base class) and write accessor methods for each attribute.
Write 2 constructors for each derived class. One with no arguments and the other which accepts the values of the attributes in the derived class as arguments.
Write a Console Application called Fleet.cs which creates and displays 2 of each Vehicle type
My code so far is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Vehicle
{
static void Main(string[] args)
{
}
class Car
{
protected string make
{
get
{
return make;
}
set
{
make = value;
}
}
protected string model
{
get
{
return model;
}
set
{
model = value;
}
}
protected int year
{
get
{
return year;
}
set
{
year = value;
}
}
protected string bodyType
{
get
{
return bodyType;
}
set
{
bodyType = value;
}
}
public bool isInitialized;
public Car()
{
isInitialized = true;
}
}
}
class Airplane
{
protected string make
{
get
{
return make;
}
set
{
make = value;
}
}
protected string model
{
get
{
return model;
}
set
{
model = value;
}
}
protected int year
{
get
{
return year;
}
set
{
year = value;
}
}
protected int numEngines
{
get
{
return numEngines;
}
set
{
numEngines = value;
}
}
protected int engineType
{
get
{
return engineType;
}
set
{
engineType = value;
}
}
}
class Boat
{
protected string make
{
get
{
return make;
}
set
{
make = value;
}
}
protected string model
{
get
{
return model;
}
set
{
model = value;
}
}
protected string year
{
get
{
return year;
}
set
{
year = value;
}
}
protected string length
{
get
{
return length;
}
set
{
length = value;
}
}
protected string hullType
{
get
{
return hullType;
}
set
{
hullType = value;
}
}
}
}
First part the OOP principles
Classes:
A class is a construct that enables you to create your own custom
types by grouping together variables of other types, methods and
events. A class is like a blueprint. It defines the data and behavior
of a type. If the class is not declared as static, client code can use
it by creating objects or instances which are assigned to a variable.
The variable remains in memory until all references to it go out of
scope. At that time, the CLR marks it as eligible for garbage
collection. If the class is declared as static, then only one copy
exists in memory and client code can only access it through the class
itself, not an instance variable. For more information, see Static
Classes and Static Class Members (C# Programming Guide). Unlike
structs, classes support inheritance, a fundamental characteristic of
object-oriented programming. For more information, see Inheritance (C#
Programming Guide).
Also objects are instances of classes.
Inheritance:
Inheritance, together with encapsulation and polymorphism, is one of
the three primary characteristics (or pillars) of object-oriented
programming. Inheritance enables you to create new classes that reuse,
extend, and modify the behavior that is defined in other classes. The
class whose members are inherited is called the base class, and the
class that inherits those members is called the derived class. A
derived class can have only one direct base class. However,
inheritance is transitive. If ClassC is derived from ClassB, and
ClassB is derived from ClassA, ClassC inherits the members declared in
ClassB and ClassA.
Derived class:
A class that was created based on a previously existing class (i.e., base class). A derived class inherits all of the member variables and methods of the base class from which it is derived.
Also called a derived type.
Method:
A method (or message) in object-oriented programming (OOP) is a
procedure associated with an object class. An object is made up of
behavior and data. Data is represented as properties of the object and
behavior as methods. Methods are also the interface an object presents
to the outside world. For example a window object would have methods
such as open and close. One of the most important capabilities that a
method provides is method overriding. The same name (e.g., area) can
be used for multiple different kinds of classes. This allows the
sending objects to invoke behaviors and to delegate the implementation
of those behaviors to the receiving object. For example an object can
send an area message to another object and the appropriate formula
will be invoked whether the receiving object is a rectangle,circle,
triangle, etc.
Attributes and properties:
"Fields", "class variables", and "attributes" are more-or-less the
same - a low-level storage slot attached to an object. Each language's
documentation might use a different term consistently, but most actual
programmers use them interchangeably. (However, this also means some
of the terms can be ambiguous, like "class variable" - which can be
interpreted as "a variable of an instance of a given class", or "a
variable of the class object itself" in a language where class objects
are something you can manipulate directly.)
"Properties" are, in most languages I use, something else entirely -
they're a way to attach custom behaviour to reading / writing a field.
(Or to replace it.)
So if you want to categorize them they are OOP(Object Oriented Programming) principles.
Second part:
Write a Console Application called Fleet.cs which creates and displays
2 of each Vehicle type.
So one way of doing this is creating vehicles as hardcoded. The other way is to ask user for vehicle details with Console.Readline(). Main method could look something like this.
static void Main(string[] args)
{
Vehicle v1 = new Vehicle { Make = "test1", Model = "model1", Year = 1996 };
Vehicle v2 = new Vehicle { Make = "test2", Model = "model2", Year = 1997 };
Console.WriteLine(v1);
Console.WriteLine(v2);
...
}
And then you would override the ToString() method for each class. Like this:
public override string ToString()
{
return string.Format("Vehicle is {0} and of model {1} and is made in {2}.", make, model, year);
}
Here you also can use base.ToString() to get the data of upper (base) class in the derivided class.
EDIT 1: User input:
So if you want the user input you could make program like this:
static void Main(string[] args)
{
//input
Vehicle v1 = new Vehicle();
Console.Write("Enter the make of 1st vehicle: ");
v1.Make = Console.ReadLine();
Console.Write("Enter the model of 1st vehicle: ");
v1.Model = Console.ReadLine();
Console.WriteLine("Enter the year of manufacturing for 1st vehicle:");
v1.Year = int.Parse(Console.ReadLine());
//output
Console.WriteLine("The data for 1st vehicle: ");
Console.WriteLine(v1);
...
}
Even better would be to create Input method in the class and calling it from Main program. So code would not be repeating itself.
Finished program
Vehicle.cs
using System;
class Vehicle
{
string make, model;
int year;
public string Make { get { return make; } set { make = value; } }
public string Model { get { return model; } set { model = value; } }
public int Year { get { return year; } set { year = value; } }
public Vehicle()
{
make = model = "Unknown";
year = 0;
}
public Vehicle(string make, string model, int year)
{
this.make = make;
this.model = model;
this.year = year;
}
public virtual void GetFromInput()
{
Console.Write("Enter the make of vehicle: ");
Make = Console.ReadLine();
Console.Write("Enter the model of vehicle: ");
Model = Console.ReadLine();
Console.WriteLine("Enter the year of manufacturing for vehicle: ");
Year = int.Parse(Console.ReadLine());
}
public override string ToString()
{
return string.Format("Vehicle is {0} and of model {1} and is made in {2}.", make, model, year);
}
}
Car.cs
using System;
class Car : Vehicle
{
string bodyType;
public string BodyType { get { return bodyType; } set { bodyType = value; } }
public Car() : base()
{
bodyType = "Unknown";
}
public Car(string make, string model, int year, string bodyType) : base(make, model, year)
{
this.bodyType = bodyType;
}
public override void GetFromInput()
{
base.GetFromInput();
Console.Write("Enter body type for the car: ");
BodyType = Console.ReadLine();
}
public override string ToString()
{
return base.ToString() + string.Format("This vehicle is a car with body type of {0}.", BodyType);
}
}
Airplane.cs
using System;
class Airplane : Vehicle
{
int noEngines;
string engineType;
public int NumberOfEngines{ get { return noEngines; } set { noEngines = value; } }
public string EngineType { get { return engineType; } set { engineType = value; } }
public Airplane() : base()
{
noEngines = 0;
engineType = "Unknown";
}
public Airplane(string make, string model, int year, int noEngines, string engineType) : base(make, model, year)
{
this.noEngines = noEngines;
this.engineType = engineType;
}
public override void GetFromInput()
{
base.GetFromInput();
Console.Write("Enter the number of engines on an airplane: ");
NumberOfEngines = int.Parse(Console.ReadLine());
Console.Write("Enter the engine type for the airplane: ");
EngineType = Console.ReadLine();
}
public override string ToString()
{
return base.ToString() + string.Format("This vehicle is an airplane with {0} engines and engine type of {1}.", NumberOfEngines, EngineType);
}
}
Boat.cs
using System;
class Boat : Vehicle
{
int length;
string hullType;
public int Length { get { return length; } set { length = value; } }
public string HullType { get { return hullType; } set { hullType = value; } }
public Boat() : base()
{
length = 0;
hullType = "Unknown";
}
public Boat(string make, string model, int year, int length, string hullType) : base(make, model, year)
{
this.length = length;
this.hullType = hullType;
}
public override void GetFromInput()
{
base.GetFromInput();
Console.Write("Enter the length of the boat: ");
Length = int.Parse(Console.ReadLine());
Console.Write("Enter the hull type for the boat: ");
HullType = Console.ReadLine();
}
public override string ToString()
{
return base.ToString() + string.Format("This vehicle is a boat with length of {0} and hull type of {1}.", Length, HullType);
}
}
Fleet.cs
using System;
class Fleet
{
static void Main(string[] args)
{
Vehicle v1 = new Vehicle();
v1.GetFromInput();
Console.WriteLine(v1);
//... for the other vehicles
}
}
This can be achieved using class inheritance.
Each of your vehicle classes, need to inherit a common class that implements functionality need by 'all' vehicles, This class (Vehicle receptively), can then be used in C# to identify any type of vehicle class/type.
Instead of having a several classes where each class is solely responsible for a type of vechile, you can abstract out common functionality needed by each vehicle, and implement a class that exposes these common relationships:
using System;
public namespace CodeSpace {
public class Vehicle {
public Vehicle(Type type, string make, string model) {
Model = model;
Make = make;
Type = type;
}
public Type VehicleType { get; private set; }
public string Make { get; set; }
public string Model { get; set; }
}
public class Airplane : Vehicle {
public class Airplane(string make, string model) : base(typeof(Airplane), make, model) {
}
}
public class Boat : Vehicle {
public class Boat(string make, string model) : base(typeof(Boat), make, model) {
}
}
public class Car : Vehicle {
public class Car(string make, string model) : base(typeof(Car), make, model) {
}
}
class Program {
public static void Main(params string[] args ) {
var vehicles = new List<Vehicle>() {
new Boat("Canoe", "X2") as Vehicle,
new Boat("Raft", "A") as Vehicle,
new Car("Ford", "T") as Vehicle,
new Airplane("BMW", "Idk") as Vehicle,
};
foreach(var v in vehicles) {
Console.WriteLine(v.VehicleType.FullName);
}
}
}
}
Now all of your vehicles can be identified using one class that exposes all vehicles through a common interface.