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;
}
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;
}
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.
Is it possible to give a C# Object like
public string Name
{
get { return _name; }
set { _name = value; }
}
a Method doing something like:
private void addTextToName(){
_name = _name + " - Test";
}
so that I can call it like
Name.addTextToName();
Because (where I come from) in JavaScript you can do such things with .prototype
Is there any way to do this in C#?
If you are asking can I add a method to a string? then yes. Look at extension methods.
public static string AddTextToName(this string s)
{
return s + " - Test";
}
Use it like this:
"Hello".AddTextToName();
Will return Hello - test.
Yes, there is a way for C# Objects (you used a string there, but though...).
Take a look at the so-called "extension methods" in C# as they are exactly what you need I think.
For further reference, look e.g. here: https://msdn.microsoft.com/en-us/library/vstudio/bb383977%28v=vs.110%29.aspx (the magic is in the this as parameter for the method)
Using the extension method.
class Program
{
static void Main()
{
Example e = new Example();
e.Name = "Hello World";
var x = e.Name;
var y = x.addTextToName();
Console.WriteLine(y);
Console.ReadLine();
}
}
class Example
{
public string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public static class MyExtensions
{
public static string addTextToName(this string str)
{
return str += " - Test";
}
}
I have the following static function in c#
public static string Greet(string name)
{
string greeting = "welcome ";
// is it possible to pass this value to a label outside this static method?
string concat = string.Concat(greeting, name);
//error
Label1.text = concat;
//I want to return only the name
return name;
}
As you can see in the comments, I want to retain only the name as the return value, however I want to be able to take out the value of the concat variable to asign it to a label, but when i try the compiler refuses, can it be done? Is there a work around?
Thank you.
If the method must be static for some reason, the main approach here would be to pass any required state into the method - i.e. add a parameter to the method that is either the label or (better) some typed wrapper with a settable property like .Greeting:
public static string Greet(string name, YourType whatever)
{
string greeting = "welcome ";
whatever.Greeting = string.Concat(greeting, name);
return name;
}
(where YourType could be your control, or could be an interface allowing re-use)
What you don't want to do is use static state or events - very easy to get memory leaks etc that way.
For example:
public static string Greet(string name, IGreetable whatever)
{
string greeting = "welcome ";
whatever.Greeting = string.Concat(greeting, name);
return name;
}
public interface IGreetable {
string Greeting {get;set;}
}
public class MyForm : Form, IGreetable {
// snip some designer code
public string Greeting {
get { return helloLabel.Text;}
set { helloLabel.Text = value;}
}
public void SayHello() {
Greet("Fred", this);
}
}
Either non-static:
public string Greet(string name)
{
const string greeting = "welcome ";
string concat = string.Concat(greeting, name);
Label1.Text = concat;
return name;
}
Or still static passing the label like Greet("John", Label1):
public static string Greet(string name, Label label)
{
const string greeting = "welcome ";
string concat = string.Concat(greeting, name);
label.Text = concat;
return name;
}
But not sure why you need to return the name in either case...if you had it when calling the function, you already have it in the scope you'd be returning to. Example:
var name = "John";
Greet(name);
//can still call name here directly
The problem is that you try to instantiate a class variable from static method.
Maybe I'm missing the point but couldn't you just do:
public static string Greet(string name)
{
return string.Concat("Welcome ", name);
}
Then use it like:
string name = "John";
label1.Text = Greet(name);
Web methods do not have to be static.