How to store the output of method? - c#

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

Related

Sending multiple parameters to a method in 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]);

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";
}
}

C# Match User Inputs to Array

I'm writing some code where I have some information about customers stored in an array called members (id, initials). I then ask the user for their id and initials and match the inputs to the stored information from array members. If they match I move on. However I get an error in my coding: "an object reference is required to access non-static field method or property". The error comes from the if statements. Any suggestions on how to correct this issue?
Some background info: I have two classes, one called Customer and one called Menu. The Menu is the main class while Customer is the class I reference from.
This is from my Menu class:
int L = 0;
string I = "";
Customer[] members = new Customer[2];
members[0] = new Customer(3242, "JS");
members[1] = new Customer(7654, "BJ");
Console.Write("\nWhat is your Loyalty ID #: ");
L =Convert.ToInt32(Console.ReadLine());
Console.Write("\nWhat is your first and last name initials: ");
I = Console.ReadLine();
if (L==Customer.GetId())
{
if (I == Customer.GetInitials())
{
Console.WriteLine("It matches");
}
}
else
{
Console.WriteLine("NO match");
}
Console.ReadKey();
}
}
}
This from my Customer class
private int id;
private string initials;
public Customer ()
{
}
public Customer(int id, string initials)
{
SetId(id);
SetInitials(initials);
}
public int GetId()
{
return id;
}
public void SetId(int newId)
{
id = newId;
}
public string GetInitials()
{
return initials;
}
public void SetInitials(string newInitials)
{
initials = newInitials;
}
The error means exactly what it says. You can't access the GetId() function of Customer by calling Customer.GetId() because GetId() only works on an instance of Customer, not directly through the Customer class.
Customer.GetId(); //this doesn't work
Customer myCustomer=new Customer(); myCustomer.GetId(); //this works
To check the user's input against your array of inputs, you need to iterate through the array (or alternatively, use Linq).
I'm going to use a generic list, because there's not really a good reason to use arrays in most cases.
List<Customer> customers=new List<Customer>();
Customers.Add();//call this to add to the customers list.
foreach(var c in customers)
{
if(c.GetId() == inputId)
{
//match!
}
else
{
//not a match
}
}
You can also improve your Customer class by using properties, or auto properties (which doesn't need a backing field). Here's an auto property example:
public string Id {get; set;} // notice there's no backing field?
Using the above auto property syntax would allow you do to this:
var customer = new Customer();
string id = customer.Id; // notice there's no parentheses?
Properties and auto properties allow for a cleaner syntax than having to write Java-style separate getters/setters.

method returning same object which was passed as parameter

Is it acceptable practice to pass an object into a method, then return the same object rather than creating a new object inside of the method itself?
As an example: if have an entity class as follows:
class UserDetails {
int UserID { get; set; }
string UserName { get; set; }
string UserAge { get; set; }
}
And then I pass an instance of this class to a method, as follows:
UserDetails UserInfo = new UserDetails();
UserInfo = Get_Details(UserInfo);
Is it reasonable for the method to do the following?
public UserDetails Get_Details(UserDetails user) {
// SQL Operations...
user.age = 32;
return user;
}
IMO, there is no need to return the object. Since it is passed to the method by reference, the caller already has a reference to the same object (with the updated values after the method completes).
On the other hand, what can be useful in some situations is a fluent-interface, where instance-methods of a class return the instance again, e.g:
class X
{
public X DoThis(int number)
{
// do something
return this;
}
public X DoThat(string name)
{
// do something else
return this;
}
}
This allows to write very readable code, such as:
var x = new X().DoThis(23).DoThat("asdf");
This can be useful with the builder pattern (when you want to build a complex object step by step).
As a very bad example:
class FooBuilder {
FooBuilder WithAge(int age);
FooBuilder WithUrl(Url url);
Foo ToFoo();
}
new FooBuilder().WithAge(12).WithUrl(new Url("http://www.happybirthday.com/").ToFoo();
In your particular case, I'd prefer to initialize everything in one go with the initializer syntax.
new User { Age = 45, UserName = "Bob", Id = 101 };
There is nothing horribly wrong with this but a couple of observations;
You are setting details inside of a method called get perhaps load is more appropriate.
If you are only passing in UserDetails because you want the id for your then the parameter should just be id instead. This keeps the interface cohesive.
It is generally considered bad form to modify a parameter object within a method, i.e., mutation principle.
Doing it like that is rather pointless, as the assignment that you do doesn't change anything.
Calling it like this:
UserInfo = Get_Details(UserInfo);
gives the same result as calling it and ignoring the return value:
Get_Details(UserInfo);
Returning the reference may only be confusing, leading someone to believe that the method returns a new instance, as that would be the only logical reason to return a reference.
It would make more sense to have that method in the class, so that you call it as:
UserInfo.Get_Details();
If your method is supposed to initialise the object, you would rather put the code it the constructor than calling it after creating the instance:
class UserDetails {
int UserID { get; set; }
string UserName { get; set; }
string UserAge { get; set; }
public UserDetails() {
Get_Details(this);
}
}
Then you just create the instance, and the constructor loads the data:
UserDetails UserInfo = new UserDetails();
This is a possible approach and when you have only ONE item to work one, the best, too. You might also consider to use ref, which creates a reference to the passed parameter
public void Get_Details(ref UserDetails user)
{
// SQL Operations. . .
user.age= 32;
}
this way, you don't pass a copy, but reference the object you passed in. But this can become quite obscure and is unnecessary in your case. See here for an insight.
You can fill your entity in its constructor method or another method inside entity class. It will be ready to use when created.
public class SomeClass
{
public string Field_1;
public int Field_2;
public SomeClass(int ID)
{
// Sql operations by ID or another value
// set fields
}
public AnotherMethod(int ID)
{
// Sql operations by ID or another value
// set fields
}
}
You might do well to look up the concepts of the Repository Pattern and OOD. In general, I prefer projections or fully loaded entities.
public UserDetailsProjection GetDetailsByUserId(Guid userID)
{
// Code goes here
return user;
}
Note: ref is not required, because all objects are passed by reference.

C# - Web Service still working despite using a class that does not have a parameterless constructor

I'm making a car auction website as a college project. The site uses a web service to do everything, and to make my life easier I made this class to store information about a car:
public class Car
{
private int id;
private string name;
private string desc;
private int startbid;
private DateTime closingdate;
public int Id
{
get
{
return id;
}
}
public string Name
{
get
{
return name;
}
}
public string Description
{
get
{
return desc;
}
}
public int StartBid
{
get
{
return startbid;
}
}
public DateTime ClosingDate
{
get
{
return closingdate;
}
}
public Car(int id, string name, string desc, int startbid, DateTime closingdate)
{
this.id = id;
this.name = name;
this.desc = desc;
this.startbid = startbid;
this.closingdate = closingdate;
}
}
Whenever I tried to view the .asmx in my browser I get an error saying this class cannot be serialized because it does not have a parameterless constructor, yet everything that uses the Car class still works just fine in the web site (eg. a page that displays information about a car shows everything with no exceptions). So the web service is still working and somehow the Car class is still being serialized. How is this possible?
EDIT: I know that to get my .asmx to show up properly I need to add public Car() {} to my class but then I also need to add set methods to every property, which I don't really want to do because these results are fetched from the database and are thus (in this case) read only. So what is the proper solution in this case? Perhaps an Obsolete attribute or something similar?
It is possible to allocate an instance of a class bypassing its constructor:
var car = (Car)FormatterServices.GetUninitializedObject(typeof(Car));
But, as MSDN remarks:
The current method should only be used for deserialization when the
user intends to immediately populate all fields.
So I guess that could be going on under the hoods for your Web Service to work.

Categories