Classes convertor - c#

I have the following class People:
class People
{
public enum Gender
{
Man = 'w',
Woman = 'f'
}
public struct Person
{
public string First, Last;
public Gender Gender;
public int Age;
public float Height, Weight;
}
public struct Group
{
public int Members;
public string Name;
}
}
Now, we are located in the class Program:
class Program
{
static void Main( string[] args )
{
People.Person p = new People.Person();
p.First = "Victor";
p.Last = "Barbu";
p.Age = 14;
p.Height = 175;
p.Weight = 62;
p.Gender = People.Gender.Man;
Console.ReadLine();
}
}
I want to put a line like this:
Console.Write( x.toString() );
How can I customize the x.toString() method, so the result to be the following in the Console
Victor Barbu
14 years
Man
175 cm
62 kg
?
Thanks in advance!

Just overrive the ToString() method
public override string ToString()
{
// return the value you want here.
}

You want to override the ToString method in the Person class. See: http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx
In your case
public class Person
{
// Snip
public override string ToString()
{
return this.First + " " + this.Last;
}
}
If you then do
Console.WriteLine(person.ToString());
The expected output would be the first and last name, you can obviously extend this to include your other fields and line breaks, etc.
Side note; what you are doing is really "pretty printing" I would suggest creating a static method "public static string PrettyPrintPerson(Person p)" or similar, to deal with textual formatting of the class.

class People
{
public override string ToString()
{
//This will return exactly what you just put down with line breaks
// then just call person.ToString()
return string.format("{1} {2}{0}{3} years{0}{4}{0}{5} cm{0}{6} kg", Environment.NewLine,
First, Last, Age, Gender, Height, Weight);
}
}

Related

CS7036:There is no argument given that corresponds to the required formal parameter 'i' [duplicate]

This question already has answers here:
C# inheritance and default constructors
(4 answers)
Inheritance with base class constructor with parameters [duplicate]
(2 answers)
Closed 1 year ago.
I am just learning C#, and I made two external classes with constructors, and one inherits from another one. But it is giving the Error:
Severity Code Description Project File Line Suppression State
Error CS7036 There is no argument given that corresponds to the required formal parameter 'i' of 'Engineer.Engineer(string)' program.cs C:\Users\win 10\Desktop\C#\program.cs\program.cs\Car.cs 41 Active
The Three Code files are:
1/ main.cs:
using System;
namespace program
{
class Core
{
static void Main(string[] args)
{
Car BMW = new Car("X-A-21-A-X", 3200000, "Reddish-brown", false);
string currentPrice = BMW.CheckPrice("us", BMW.price);
if(!double.TryParse(currentPrice, out var q))
{
Console.WriteLine(currentPrice);
}else if(double.TryParse(currentPrice, out var z))
{
double converted_Price = Convert.ToDouble(currentPrice);
Console.WriteLine(converted_Price);
}
Console.WriteLine(BMW.model);
}
}
}
2/ Car.cs:
using System;
namespace program
{
class Car : Engineer
{
private string _model;
public string model
{
get { return _model; }
set { _model = value; }
}
public double price;
public string color;
public bool available;
public string CheckPrice(string locale, double price)
{
string ret = default(string);
if(locale == "in")// India
{
ret = Convert.ToString(2.14 * price);
}else if(locale == "us")// USA
{
ret = Convert.ToString(3.98 * price);
}else if(locale == "jp")// Japan
{
ret = Convert.ToString(1.3 * price);
}else if(locale == "vn")//Vietnam
{
ret = Convert.ToString(0.78645 * price);
}else if(locale == "ch")//China
{
ret = Convert.ToString(2.56 * price);
}
else
{
ret = "Invalid Locale, Your Country does not ship the car.";
}
Console.WriteLine(_model);
return ret;
}
public Car(string modelName, double priceVal, string ColorName, bool avail) /* 'Car' in this line is causing problems*/
{
model = modelName;
price = priceVal;
color = ColorName;
available = avail;
}
}
}
3/ Engineer.cs:
using System;
namespace program
{
class Engineer
{
private string creatorCompany;
public string creator_Company
{
get { return creatorCompany; }
set { creatorCompany = value; }
}
public Engineer(string i)
{
creator_Company = i;
}
}
}
There are answers there but I can't understand them. Please explain them to me like I'm a monke who doesn't know sh*t
You need to add the default constructor to the Engineer class. because when you create an instance of derived it calls the base class constructor before the derived class constructor.
public Engineer()
{
}
If Car is Engineer
In the unlikely scenario that Car is Engineer the Car needs to supply creatorCompany:
Engineer definition states that creatorCompany must be supplied
Car is Engineer
Car must provide creatorCompany.
It could look something like this:
public Car(
string creatorCompany, // Added
string modelName,
double priceVal,
string ColorName,
bool avail)
: base(i: creatorCompany) // Added
{
model = modelName;
price = priceVal;
color = ColorName;
available = avail;
}
If Car is not Engineer
In this case, the solution is to remove : Engineer:
class Car : Engineer
becomes:
class Car
In the constructor of the child class you must reference the parameters of the parent/base class.
In this case change the constructor of the Car class to the following.
//Inside class Car
public Car(string i, string modelName, double priceVal, string ColorName, bool avail) : base(i)
{
//Code inside
}
This is all that cause an issue not anything else.

Not able to print value of an array while using inheritance in C# [duplicate]

This question already has answers here:
printing all contents of array in C#
(13 answers)
Closed 2 years ago.
I am trying to print from an array in an exercise using inheritance and polymorphism...etc
The exercise is a student and teacher class that inherit from a Person class but display different results by overriding the the print method in both classes. The teacher class prints from string variables but the student class prints from a string variable and an array of strings. I was able to print everything but the part where i print the Array of string i get System.String[] which i understand as it's printing the name of the object instead of the value. I tried overriding the To.String method to pass it the printDetails method but since my printDetails method has a return type void, i can't do that.
Below is my code for reference:
Program.cs :
namespace Task3
{
class Program
{
static void Main(string[] args)
{
var people = new List<Person>();
string[] subjects = { "Math", "Science", "English" };
string studentName = "Sue";
Student student = new Student(studentName, subjects);
people.Add(student);
string faculty = "Computer Science";
string teacherName = "Tim";
Teacher teacher = new Teacher(teacherName, faculty);
people.Add(teacher);
foreach (var element in people)
{
element.PrintDetails();
}
Console.ReadKey();
}
}
}
Person.cs :
namespace Task3
{
public abstract class Person
{
protected string _name;
public Person(){}
public Person(string name)
{
_name = name;
}
public abstract void PrintDetails();
}
}
Student.cs :
namespace Task3
{
public class Student : Person
{
private string[] _subjects;
public Student(string name, string[] subjects) : base(name)
{
_subjects = subjects;
}
public override void PrintDetails()
{
Console.WriteLine("Hi my name is " + _name + " and I am studying " + _subjects);
}
}
}
Teacher.cs :
namespace Task3
{
public class Teacher : Person
{
private string _faculty;
public Teacher(string name, string faculty) : base(name)
{
_faculty = faculty;
}
public override void PrintDetails()
{
Console.WriteLine($"Hi my name is {_name} and I teach in the {_faculty} faculty");
}
}
}
Below is the output i get and the output i should get:
Your PrintDetails() method is printing the array without any kind of formatting (hence it's just printing the array type)
use string.Join to print the array delimenated by commas
public override void PrintDetails()
{
Console.WriteLine("Hi my name is " + _name + " and I am studying " + string.Join(",", _subjects));
}
ought to do it.

Pass enum as a parameter in C# or any alternatives

public EnumA
{
name = 1,
surname = 2
}
public EnumB
{
name = 50,
surname = 60
}
public void myMethod(User u,Enum e)
{
//Enum e can be either EnumA or EnumB
//Do something with the Enum Passed
}
Let's say I have the above code but instead of specifiying the Enum in the method like I'm doing above, I'd like to select the enum which is passed through the method parameter. Is there any way of doing so?
You can do this via reflection, but I'm worried that you don't understand enumerations properly. It kind of looks to me like you are trying to use them as class instances to hold arbitrary data, in which case, you really should be using a real class.
In case I'm wrong, I've included code below to do what you are asking for, but I don't think it will be very useful for you.
void Main()
{
Test(EnumA.First);
Console.WriteLine("-----");
Test(EnumB.B);
}
void Test(Enum theEnum)
{
Type t = theEnum.GetType();
foreach (string element in Enum.GetNames(t))
{
Debug.WriteLine(element + " = " + (int) Enum.Parse(t, element));
}
}
enum EnumA
{
First = 1,
Second = 2
}
enum EnumB
{
A = 1,
B = 2,
C = 3
}
It generates the following output:
First = 1
Second = 2
-----
A = 1
B = 2
C = 3
I think this is more what you are trying to do though:
void Main()
{
Person A = new Person()
{
Name = "John",
Surname = "Doe"
};
Person B = new Person()
{
Name = "Jane",
Surname = "Doe"
};
A.ShowInfo();
Console.WriteLine("----");
B.ShowInfo();
}
class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public void ShowInfo()
{
Debug.WriteLine("Name=" + Name);
Debug.WriteLine("Surname=" + Surname);
}
}
It output the following:
Name=John
Surname=Doe
----
Name=Jane
Surname=Doe
Have you tried the following:
public void myMethod(User u,Enum e)
{
if (e is EnumA)
{
EnumA ea = (EnumA)e;
// Do something with ea
}
else if (e is EnumB)
{
EnumB eb = (EnumB)e;
...
}
}
you have use generic type for this operation.
below code is showing a sample code (as Console app);
class Program
{
static void Main(string[] args)
{
myMethod<EnumA>("deneme", EnumA.name);
}
public enum EnumA
{
name = 1,
surname = 2
}
public enum EnumB
{
name = 50,
surname = 60
}
public static void myMethod<T>(string u, T e)
where T : struct,IConvertible
{
if (typeof(T) == typeof(EnumA))
{
Console.WriteLine("EnumA");
}
else if (typeof(T) == typeof(EnumB))
{
Console.WriteLine("EnumB");
}
Console.ReadLine();
}
}
You could use overloading:
public void myMethod(User u, EnumA e)
{
// Call a function common to both
}
public void myMethod(User u, EnumB e)
{
// Call a function common to both
}
I guess C# 7.3 allows you to do something like:
public void myMethod(User u, TEnum e) where TEnum : Enum
{
//Enum e can be either EnumA or EnumB
//Do something with the Enum Passed
}
I used something like this for a pre-7.3 project and it was a little ugly, but WAY better and more readable than any other way I could find:
public void myMethod(User u, object e)
{
// Test to make sure object type is either EnumA or EnumB
// Call a function common to both
// object e can be either EnumA or EnumB by casting like ((EnumA)e) or ((EnumB)e)
}
This is not how enums behave (or should behave). You're basically creating two different instances of enums. This is why classes exist in C#. Consider creating a class:
public class SomeEnum
{
public int Name;
public int Surname;
private SomeEnum(int name, int surname)
{
Name = name;
Surname = surname;
}
public static SomeEnum EnumA => new SomeEnum(1, 2);
public static SomeEnum EnumB => new SomeEnum(50, 60);
}
And changing your method to this:
public void myMethod(User u, SomeEnum e)
{
// Enum e can be either EnumA or EnumB
// Do something with the Enum passed
}
I changed as least code as possible as I'm not sure what the purpose is of these 'Enums', but this way you'll be able to create as many instances as you want, without your code getting messy with all of these identical Enum specifications.
To use this method with EnumA for example you can call myMethod(user, SomeEnum.EnumA).
This way it's only possible to use the specified enums (EnumA and EnumB). Alternatively, if you want to create enums on-the-fly, the code can be changed to:
public class SomeEnum
{
public int Name;
public int Surname;
public SomeEnum(int name, int surname)
{
Name = name;
Surname = surname;
}
}
This way you can call the method with myMethod(user, new SomeEnum(1, 2)).

Array.find() provides strange results

I am in middle of writing an assignment for my part time programming course. The issues with my code is the array.find() and results of that search. It should(In my theory) search the array for information and then post them to the user, however what comes out from all of the searches is the same thing: ass2task1.Program+customer Here are only parts of the code becouse out teacher told us we can post question on the internet as long as we don't post our entire codes
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
}
static void Main(string[] args)
{
customer[] customerdetails = new customer[99];
int selector = 0;
int selector2 = 0;
string vtemp = "";
string ctemp = "";
int searchnumber;
string searchforename; //variable/ array declaring
string searchsurname;
string searchtown;
DateTime searchdob;
customer resultnumber;
customer resultforename;
customer resultsurname;
customer resulttown;
customer resultdob;
if (selector2 == 2)
{
Console.Clear();
Console.WriteLine("Enter the forename you are looking for: ");
searchforename = (Console.ReadLine());
resultforename = Array.Find(customerdetails, customer => customer.customerforname == searchforename);
Console.Clear();
Console.WriteLine("Enter the surname you are looking for: "); // all of the searches comes out with ass2task1.Program+customer result
searchsurname = (Console.ReadLine());
resultsurname = Array.Find(customerdetails, customer => customer.customersurname == searchsurname);
Console.WriteLine("The forename resuts:" + resultforename);
Console.WriteLine("The surname resuts:" + resultsurname);
Array.Find() will return the object that matches a predicate, if you want the property value, you would need to do something like: resultforename.customerforname or something similar.
If it is not found, then a default value will be returned, so check for nulls etc.
When you convert an object to a string ("The forename resuts:" + resultforename) it calls the objects ToString() method. Define an appropriate ToString() method:
struct customer
{
public int customernumber;
public string customersurname;
public string customerforname;
public string customerstreet;
public string customertown;
public DateTime customerdob;
public override string ToString()
{
return customersurname + ", " + customerforname;
}
}
To (attempt to) expand on Ric and clcto's answers. The reason you're getting the struct name in your
Console.WriteLine("The forename resuts:" + resultforename);
Console.WriteLine("The surname resuts:" + resultsurname);
Your resultforename is of struct customer - by default Console.WriteLine(struct) does not know how to represent a complex object as a string.
As suggested you could do
Console.WriteLine("The forename resuts:" + resultforename.customerforname);
Or provide your own .ToString() method for the struct as clcto pointed out - doing this you're basically telling Console.WriteLine (or any string representation) how to represent a struct of customer as string.
Don't know if this will help, or make it even less clear. But given:
public struct Foo
{
public string Bar { get; set; }
}
public struct FooTwo
{
public string Bar { get; set; }
public override string ToString()
{
return "This is how to represent a Foo2 as string: " + Bar;
}
}
Foo[] foos = new Foo[99];
Foo foundFoo = foos[0]; // This is equivalent to your find statement... setting a foundFoo local variable to a Foo struct
string foundBar = foos[0].Bar; // This is another way to get to what you're trying to accoomplish, setting a string value representation of your found object.
Console.WriteLine(foundFoo); // Doesn't know how to deal with printing out a Foo struct - simply writes [namespace].Foo
Console.WriteLine(foundFoo.Bar); // Outputs Foo.Bar value
Console.WriteLine(foundBar); // Outputs Foo.Bar value
FooTwo foo2 = new FooTwo();
foo2.Bar = "test bar";
Console.WriteLine(foo2); // outputs: "This is how to represent a Foo2 as string: test bar"

Add a space in this string between words [duplicate]

This question already has answers here:
Enum ToString with user friendly strings
(25 answers)
Using [Display(Name = "X")] with an enum. Custom HtmlHelper in MVC3 ASP.Net
(3 answers)
Closed 9 years ago.
Tried setting up an enum that has spaces in attributes but was very hard so figured their might be an easy way to hack this with a string format or something since their is only one enum that I need that has spaces and I know exactly what it is. Any helping wiht adding a space to this string
public class Address
{
...blah...more class datatypes here...
public AddressType Type { get; set; } //AddressType is an enum
...blah....
}
if (Address.Type.ToString() == "UnitedStates")
{
**Add space between United and States**
}
If your enum entries are in camel case, you can insert a whitespace before the upper letter
string res = Regex.Replace("UnitedStates", "[A-Z]", " $0").Trim();
You can create your own ToString method on the enumeration using an extension method.
public static class AddressTypeExtensions
{
public static string ToMyString(this AddressType addressType)
{
if (addressType == AddressType.UnitedStates)
return "United States";
return addressType.ToString();
}
}
This is a neat trick I found yesterday (in 2009). I wonder why I never thought of it myself. In the .net framework there is no way how to control .ToString() for enumerations. To work around that an extension method can be created as well as an attribute to decorate the different values of the enumeration. Then we can write something like this:
public enum TestEnum
{
[EnumString("Value One")]
Value1,
[EnumString("Value Two")]
Value2,
[EnumString("Value Three")]
Value3
}
EnumTest test = EnumTest.Value1;
Console.Write(test.ToStringEx());
The code to accomplish this is pretty simple:
[AttributeUsage(AttributeTargets.Field)]
public class EnumStringAttribute : Attribute
{
private string enumString;
public EnumStringAttribute(string EnumString)
{
enumString = EnumString;
}
public override string ToString()
{
return enumString;
}
}
public static class ExtensionMethods
{
public static string ToStringEx(this Enum enumeration)
{
Type type = enumeration.GetType();
FieldInfo field = type.GetField(enumeration.ToString());
var enumString =
(from attribute in field.GetCustomAttributes(true)
where attribute is EnumStringAttribute
select attribute).FirstOrDefault();
if (enumString != null)
return enumString.ToString();
// otherwise...
return enumeration.ToString();
}
}
[TestMethod()]
public void ToStringTest()
{
Assert.AreEqual("Value One", TestEnum.Value1.ToStringEx());
Assert.AreEqual("Value Two", TestEnum.Value2.ToStringEx());
Assert.AreEqual("Value Three", TestEnum.Value3.ToStringEx());
}
The credit goes to this post.
I have a handy Extension method for exactly this
public static class EnumExtensions
{
public static string ToNonPascalString(this Enum enu)
{
return Regex.Replace(enu.ToString(), "([A-Z])", " $1").Trim();
}
public T EnumFromString<T>(string value) where T : struct
{
string noSpace = value.Replace(" ", "");
if (Enum.GetNames(typeof(T)).Any(x => x.ToString().Equals(noSpace)))
{
return (T)Enum.Parse(typeof(T), noSpace);
}
return default(T);
}
}
Example:
public enum Test
{
UnitedStates,
NewZealand
}
// from enum to string
string result = Test.UnitedStates.ToNonPascalString(); // United States
// from string to enum
Test myEnum = EnumExtensions.EnumFromString<Test>("New Zealand"); // NewZealand
The following code will convert AbcDefGhi to Abc Def Ghi.
public static string ConvertEnum(this string value)
{
string result = string.Empty;
char[] letters = value.ToCharArray();
foreach (char c in letters)
if (c.ToString() != c.ToString().ToLower())
result += " " + c;
else
result += c.ToString();
return result;
}

Categories

Resources