Sending multiple parameters to a method in C#? - c#

Sending multiple parameters to a method?
So, i am pretty new to C# and Visual Studio and i am "learning by doing" and asking questions. I am writing a small Windows Form application.
I am trying to send another form values.
I have a list of objects from this class:
class Cars
{
public string Name { get; private set; }
public string Color { get; private set; }
public Cars(string name, string color)
{
this.Name = name;
this.Color = color;
}
}
So in my Form1 i have access to these objects by using:
List<Cars> cars = new List<Cars>();
This list of Cars is loaded in other methods.
So now, i am trying to send another form (Edit form) a car.
I would like to do this:
var form2 = new frmEdit(cars[0]);
But then compiler complains about that i need to set my class to public...bad OOP. So then i could do it like this:
var form2 = new frmEdit(cars[0].Name,cars[0].Color);
Fine! But if this was another language like Javascript or PHP i would have sent an object. So i have read about "Anonymus Types" in C# so i thought that could be a good solution.
But the receiveing form doesn´t know about that...so it will complain if i use it like this:
car.Name;
So what should i do here? I am trying to use at least "some" good OOP so i think it is a bad solution making the Cars class public. The Edit form does not need to know about the Cars class.
Thank you for any advice!
[EDIT]
Edit form constructor:
public frmEdit(string name, string color)
{
textName.Text = name;
textColor.Text = color;
}

Change your frmEdit to:
private Cars myCar; // add this var.
public frmEdit(Cars car)
{
this.myCar = car; // now you have your car stored if you need
textName.Text = car.Name;
textColor.Text = car.Color;
}
And Then:
var form2 = new frmEdit(cars[0]);

Related

Suggesting options from two List<string> objects separated by a comma in C#

I have an AutoSuggestBox in my application. It suggests city names from a List object, which is deserialized from a json file. I also have another List object that contains the country names. What I want to do is suggesting the options in city_name,country_name format. How do I do this?
I suppose there is a way to pass something like DisplayValue on your AutoSuggestBox which must point to a property in your class. Let's say:
List<MyObject> list = new List<MyObject>(); // Simulate already deserialzied list
myAutoSuggestBox.ItemsSource = list;
myAutoSuggestBox.DisplayValue = "Combined";
public class MyObject
{
public string City { get;set; }
public string Country { get;set; }
public string Combined
{
get
{
return $"{City}, {Country}";
}
}
}
P.S. I don't know if it's a desktop or web application, but that's the main idea with a desktop app.

Making a Subclass with one parameter to change a value of Parent Class

Hi guys I need some help. I'm completely suck on how to do this with Inheritance.
The aim is to change the value of 'Name' property inherited by the Parent Class (Clothing) of a shirt object. When a button is clicked withing my C# Web Form by calling the Shirt's method of "ReNameShirt()" to change the name and then display the new 'name'.
My teacher hinted me by saying to use a subroutine. Still lost.
Can you help me out? Much Appreciated.
Clothing Class
using System;
//THE PARENT CLASS 'Clothing'
public class Clothing
{
public string _name;
public string _size;
public string name {get; set;}
public string size {get; set;}
}
//SUBCLASS OF 'Trousers'
public class Trousers : Clothing
{
public string LegLength { get; set; }
public Trousers()
{
LegLength = "91";
}
}
public class Shirt : Clothing
{
public string ReNameShirt()
{
Shirt Po = new Shirt();
Po.name = "blue shirt";
return ReNameShirt();
}
within the Inheritance.aspx.cs file:
protected void Button2_Click(object sender, System.EventArgs e)
{
Shirt myShirt = new Shirt();
myShirt.name = "red polo";
myShirt.size = "85";
Label2.Text = "<b>Name:</b> " + myShirt.name + " <b>Size</b> " + myShirt.size;
myShirt.ReNameShirt();
Label3.Text = myShirt.size;
}
}
Your shirt already exists so there is no need for you to create an instance of it. Doing that isn't modifying "this shirt." It's like if you told me "dye this shirt blue" and instead I said "here is another blue shirt" but then threw it away (because the variable goes out of scope). Your next problem is you are doing recursion. Since it sounds like you're new to programming, let me explain. Recursion is when a method (what your professor is calling a subroutine, another term for it) calls itself. That's OK, but you need it to end at some point. In your case, your method will call itself until you overflow the stack (get it... stackoverflow?) and the program can't make any more calls so it will crash. When ever you do recursion, you need to make sure there is a way to end it. Classic recursion problems are like factorial where it is defined as n*(n-1) factorial, but the way it ends is 1! Is just defined as 1, so once n-1 =1, I don't factorial any more, I just return 1.
public class Shirt : Clothing
{
public void ReNameShirt()
{
// Shirt Po = new Shirt(); You are a shirt, there is no need to create one.
name = "blue shirt";
// return ReNameShirt(); This will cause infinite recursion and crash.
}
Your ReNameShirt method isn't doing what you thing it's doing. It's instantiating a new Shirt and will cause recursion rather than changing the shirt's name. Change it to:
public void ReNameShirt()
{
this.name = "blue shirt";
}
Your problem is that you are creating a new instance inside your method and updating the value of this instance.
Your function should be something like that:
public class Shirt : Clothing
{
public void ReNameShirt()
{
name = "blue shirt";
}
}

List in C# throws error variable is a "field" but is used as a "type"

Basicly, i need an list of objects sporocilo, but when i try to fill it the way someone explained on this forum, I get the error:e-posta.mainwindow.sporocila is a "field" but is used as a "type" and I don't know how am I supposed to solve this.
public class sporocilo
{
string mapa;
string posiljatelj;
string prejemnik;
string vsebina;
public sporocilo(string m, string p, string pr, string vs)
{
mapa = m;
posiljatelj = p;
prejemnik = pr;
vsebina = vs;
}
public string getPosiljatelj()
{
return posiljatelj;
}
};
List<sporocilo> sporocila = new List<sporocilo>();
sporocila.add(("Prejeto","jan.mlinar#gmail.com","rok.sekalo#gmail.com","VSEBINA"));
I've put this code right after
public partial class MainWindow : Window
{
I'd also like to know how to access the list later, for example with an array, i'd do a for statement which would loop through it, how can I loop through the list ?
Should be
List<sporocilo> sporocila = new List<sporocilo>();
sporocila.Add(new sporocilo("Prejeto","jan.mlinar#gmail.com","rok.sekalo#gmail.com","VSEBINA"))
First, this has to be in the constructor
Second the Add method is with a capital A.
Yeah and third
sporocila.Add(new sporocilo("Prejeto","jan.mlinar#gmail.com","rok.sekalo#gmail.com","VSEBINA"))
You could put your class public class sporocilo into a separate file.
Put the rest of your code e.g. in the constructor of MainWindow, like this:
public partial class MainWindow : Window {
public MainWindow()
{
List<sporocilo> sporocila = new List<sporocilo>();
sporocila.Add(new sporocilo("Prejeto","jan.mlinar#gmail.com","rok.sekalo#gmail.com","VSEBINA")
}
}

How to store the output of method?

I am looking for easy way to store the output of the method in some sort of variable so that it can be used by another class.
For example:
partial class Form1 {
public string orderNumber() {
string ord="ORD"+get_next_id()+DateTime.Now.Year;
return ord;
}
}
In an instance of Form1 user enter the purchase details such as name, address... and when user clicks add entry button, the details is saved in the database with ordernumber generated by above code. In meantime when user click add entry, it kills the current form and bring up the another form which uses the ordernumber generated earlier. When I do like
Form1 m=new Form1();
and do something like(following is pseudo code)
m.orderNumber=string orderNUm.
It generates different order number which I don't want. I want to use the ordernumber that was saved in the database by the Form1.
I want to store that ord somewhere so that I can pass it to another class.
Another class can use the result simply by calling the method itself:
public class A
{
public string orderNumber()
{
string ord = "ORD" + get_next_id() + DateTime.Now.Year;
return ord;
}
}
public class B
{
public void DoSomeWork()
{
A a = new A();
string result = a.orderNumber();
}
}
The notion of "storing it somewhere" feels like the concept of a global variable. While one can accomplish essentially the same thing, that is to be discouraged as that does not represent object oriented design principals.
Just to understand how you could do that in C# (you should not do this), you could do:
static public SharedStorage
{
public string OrderNumber { get; set; }
}
// Somewhere in your code
SharedStorage.OrderNumber = a.orderNumber();
// Somewhere else in your code
string orderNumber = SharedStorage.OrderNumber;
If you want to set an order number on an instance once and then use it going forward, you could put the logic in the constructor:
public class A
{
public string OrderNumber { get; private set; }
public A()
{
OrderNumber = "ORD" + get_next_id() + DateTime.Now.Year;
}
}
// Somewhere else in your code
A a = new A();
string orderNumber = a.OrderNumber;
This is fairly basic stuff, but add this to the top of the class:
public string OrderCode;
Next add OrderCode = ord; above the return ord; line
Now whenever someone needs the ordercode they just make a call to <YourClass>.OrderCode
However, they could just call the method itself to get the order number as it is public.
PS: the orderNumber method doesn't follow c# conventions. a) it should be properly capitalized (OrderNumber) and b) a more meaningful name would be GetOrderNumber

C# - class instantiating other classes?

I'm a C# beginner and am struggling a little bit with how classes relate to one another.
I am trying to code up a very simple elevator simulation. I have a class for Elevator:
class Elevator
{
public int currentFloor;
public Elevator()
{
currentFloor = 0;
}
public void ascend()
{
currentFloor++;
}
public void descend()
{
currentFloor--;
}
}
Very simple. This works, I can instantiate a new elevator object and have it go up and down, etc...
Now, I want to create a building object, so I created a new class for Buildings. However, I am now stuck - how do I add variable amounts of elevator objects to my buildings? For example, I might want to instantiate a building with 3 elevators, or another with 5...
I started creating a solutiomn where the building class has a List of elevators I can dynamically add to, but that seems so obtuse. So what I am looking for is something like:
Building office = new Building();
office.elevator1 = new Elevator();
office.elevator2 = new Elevator();
which obviously doesn't work because I don't have elevator1 and elevator2 declared in the Building class. What is the best/cleanest way to accomplish what I am looking to do? Also, what is this called? I Googled a ton of terms - class belongs to another class, instantiating a class from another class, similar terms with object instead of class... I've also looked over some of the elevator simulator code out there, but couldn't find anything dynamic like I'm looking for...
Having a List<Elevator> is quite appropriate here; it describes the real-world model very well.
Perhaps it would be better if it were an Elevator[] (in the sense that perhaps it should not be possible to change the number of installed elevators after the building has been erected), but that's not absolute.
In any case, the collection of elevators should be exposed as a read-only property of appropriate type because it doesn't make sense to swap it with another one.
You can add member of type equal to List<Elevator> nd inject inside constructor
Sample
public class Building
{
private List<Elevator> yourList;
public Building(List<Elevator> value)
{
yourList = value;
}
}
Use case :
var list = new List<Elevator>();
list.Add
.....
var building = new Building(list);
Here's an alternative:
class Building
{
public List<Elevator> Elevators { get; set; }
public Building(params Elevator[] elevators)
{
Elevators = elevators.ToList();
}
}
The you can do:
var building = new Building(new Elevator(), new Elevator(), new Elevator());
And add more later:
building.Elevators.Add(new Elevator());
Depends. Say your building will only ever have one elevator. You'd want to do something like this:
public class Building
{
public Elevator Elevator { get; set; }
}
Then when you create the building like you did in your code above, you can do something like this:
office.Elevator = new Elevator();
You're new to C#, so you may not have really been exposed to Properties yet (more reading). Cliffs on Properties: they're creating a way for you to get and set data about your object. In this example, we're getting/setting the Elevator.
Now, if your building is going to have an unknown amount of elevators, you can't just write properties for Elevator1 to ElevatorInfinity. That's when you'll want to use a collection of some sort. As others have posted in here, you can do this like so:
public class Building
{
public IList<Elevator> Elevators { get; set; }
}
And to add an elevator to your building:
// Make sure you instantiate the list! For practice, you should run this code without instantiating the list, so you can see what happens.
office.Elevators = new List<Elevator>();
office.Elevators.Add(new Elevator());
More reading on IList
I think you can override indexer. Of course, you should backbone it with List. Lists are ok.
namespace Tests_CSharp_Indexer
{
class Elevator
{
}
class Building
{
public class ElevatorList
{
private List<Elevator> elevators = new List<Elevator>();
public Elevator this[int i]
{
get
{
return elevators[i];
}
set
{
if (i == elevators.Count)
{
elevators.Add(value);
}
else
{
elevators[i] = value;
}
}
}
public int Count {
get
{
return elevators.Count;
}
}
}
public readonly ElevatorList Elevators = new ElevatorList();
}
class Program
{
static void Main(string[] args)
{
Building building = new Building();
building.Elevators[0] = new Elevator();
building.Elevators[1] = new Elevator();
building.Elevators[2] = new Elevator();
Console.Out.WriteLine(building.Elevators.Count);
}
}
}

Categories