Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have to create class like DataBase that will contain menu, adding users, editing them, deleting etc.
Users are from class User.
It looks like:
class base
{
protected int mAccounts=0;
protected const int mMaxAccs=10;
osoba[] list = new osoba[mMaxAccs];
public void menu(){...}
public void add()
{
user user1("Jurand","ze Spychowa",15231512,"1410-10-26","hue#x.com");
mAccounts++;
}
... useless code there
}
then there is User class
class user
{
private string mName;
private string mSurname;
private int mPesel;
private DateTime mBDate;
private string mEmail;
osoba(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
The problem is adding new accounts. I totally don't know how to make it working
So the users will be stored in base class and you will have access to edit and add them etc.
Anyone know how to make it working (Creating objects properly)?
I suggest adding properties to User class:
class User
{
public string mName { get; private set; }
public string mSurname { get; private set; }
public int mPesel { get; private set; }
public DateTime mBDate { get; private set; }
public string mEmail { get; private set; }
//constructor for User class
public User(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
}
and modify your add method (also changed object where you store data from array to List):
class MyDB
{
List<User> list = new List<User>();
public void add()
{
//use constructor to create new object
User person = new User("Jurand", "ze Spychowa","15231512","1410-10-26","hue#dupa.com");
//add object to list
list.Add(person);
}
}
Its not good idea to mix different languages in code so try avoiding naming objects/methods like "osoba".
You will probably benefit from reading following articles (in Polish):
C# Constructors
C# Properties
I belive that only thing that is missing in your add() method is:
osoba[mAccounts] = user1;
before mAccounts++ line.
Make fields public only if your User class is going to be stupid data object which only store data and contain no methods (maybe except formatting, converting etc.).
Related
This question already has answers here:
Use a variable from another method in C#
(2 answers)
Closed 1 year ago.
This seems like an easy question to find the answer to, but I can't find anything quite like this.
I have a class file named Earnings.cs, that will only hold two items (lastYear, thisYear).
The code I have is as follows
public void parseEarnData(List<String> earningData)
{
... //gets the information
classAdd(lq1, lq2, lq3, lq4, tq1, tq2, tq3, tq4);
}
public void classAdd(string lqO, string lqT, string lqTh, string lqF, string tqO, string tqT, string tqTh, string tqF)
{
Earnings lastYear = new Earnings(Convert.ToDecimal(lqO), Convert.ToDecimal(lqT), Convert.ToDecimal(lqTh), Convert.ToDecimal(lqF));
Earnings thisYear = new Earnings(Convert.ToDecimal(tqO), Convert.ToDecimal(tqT), Convert.ToDecimal(tqTh), Convert.ToDecimal(tqF));
}
Then in a method that actually does math, I would like to retrieve lastYear and thisYear. Everything in the class is public, but lastYear and thisYear do not exist in the context of the method for calculations. So my question is how do I access them?
Class if you think it's important
public class Earnings
{
public decimal q1 { get; set; }
public decimal q2{ get; set; }
public decimal q3{ get; set; }
public decimal q4{ get; set; }
public Earnings(decimal q1, decimal q2, decimal q3, decimal q4)
{
this.q1 = q1;
this.q2 = q2;
this.q3 = q3;
this.q4 = q4;
}
}
Edit: The variable names just stand for Last Quarter One, Two, etc. and This Quarter One, Two, etc. Sorry for the weird abbreviations.
Edit 2: All the code is written within my Form's class (Form1.cs), and the method that will do the calculations on the data will also be located within the same class. I just want to be able to access the data from the Earnings class in my main code.
All the code is written within my Form's class (Form1.cs), and the method that will do the calculations on the data will also be located within the same class.
Then you'll probably want to make lastYear and thisYear part of your form too:
public partial class Form1 : Form
{
// declare Earnings members
Earnings lastYear;
Earnings thisYear;
// ...
public void classAdd(string lqO, string lqT, string lqTh, string lqF, string tqO, string tqT, string tqTh, string tqF)
{
// assign values to declared instance members
lastYear = new Earnings(Convert.ToDecimal(lqO), Convert.ToDecimal(lqT), Convert.ToDecimal(lqTh), Convert.ToDecimal(lqF));
thisYear = new Earnings(Convert.ToDecimal(tqO), Convert.ToDecimal(tqT), Convert.ToDecimal(tqTh), Convert.ToDecimal(tqF));
}
public void doActualWork()
{
// now you can access lastYear and thisYear in this scope too
}
}
It's not important which source code file contains the definition for Earnings - it's just a blueprint we can use elsewhere :-)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm new to C# and I can't find the right things to search for. I'm trying to understand the difference between these three types of syntax:
public string Topic(){}
public class Topic{}
public string Topic{}
I know the 1st is a function and the 2nd is a class, but what confuses me is what the 3rd is.
question
what is #3 called and how is it used?
Anything that could provide clarity please.
The 3rd is a property. The most common representation in C# is autogenerated properties, like this:
public string Topic { get; set; }
Which is equivalent to:
private string _topic;
public string Topic
{
get { return _topic; }
set { _topic = value; }
}
It should be used to hold internal states of the object.
It can be a readonly property, with getter only:
public string Topic { get; }
Or only with setter:
public string Topic { set; }
You can also apply accessibility modificators in getters and setters, for example:
public string Topic { protected get; private set; }
The third is a property, when used correctly. It's basically a variable with built in getter and setter.
public string Topic {get; set;}
This automatically creates a string variable which allows you to set or get directly via Topic = "new topic"
public string Topic {get; private set; }
allows public access to read the value but only the local class can set it.
Often, when more complexity is required than simply setting/getting, they are used with another backing value:
string _topic;
public string Topic {
get { return _topic; }
set { _topic = value; }
}
The third one is a property in C#. For example, you can have a person object (read class) with few properties. To get and set values for those properties, you use this kind of syntax.
public class Person
{
private string _name = "";
public int Id { get; set; }
public string Name {
get{
return "Jonathan";
}
set{
this._name = value;
}
}
}
Here Person has two properties namely Id and Name. The property syntax for Id is using "Automatic Property" syntax, which means someone can get and set this property like this:
var person = new Person();
person.Id = "1";//set Id value
//Or get Id value like this
var personId = person.Id;
The Name property is being set explicitly. When you request it, the hard coded value "Jonathan" will be returned and when setting, whatever value is assigned, will be set.
You can read more about properties here https://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx
Hope this helps.
The third forms a property function. It lives inside of a class. For example:
public string MyProperty { get; set; }
To find out more you should look up encapsulation.
This is a shorthand:
This is getting and setting automatically, which is why they are called Auto-Implemented Properties. These two defined properties below are one & the same.
public class Constituent{
public string Name {get; set;} //This is a property,
public string Name //This is a property, The value can only be of type **string** because we've assigned it that datatype, which would also be the return type.
{
get { return _name; }
set { _name = value; }
}
}
You can also use access modifiers private, public, protected on them.
This will determine Whether you can you get & set the property value.
public string Name {get; private set; }
In order to be be able to access the property you need to instantiate the Class(Constituent).
An example of how you can instantiate would be:
var constituent = new Constituent();
constituent.Name = "Jonathon"; //Setting the value of Name property.
var Member_Name = constituent.Name; //Storing a value into a variable
Hope this Helped you. Auto-Implemented Properties
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Today i am trying to add another info into a class but i am unable to add. I have tough of adding another class but i am sure that there is a way to modify the class to add more Info.
The info i want to add is
Mr Chan, 1200, 18 Pioneer Rd and
Mr Lee, 600, Blk 21 #21-21 Yishun Rd
class PersonalInfo
{
private string name;
private float salary;
private string address;
public PersonalInfo(string nameVar, float salaryVar, string addressVar)
{
name = nameVar;
salary = salaryVar;
address = addressVar;
}
public void PrintPersonalInfo(TextBox txtPersonalInfo)
{
txtPersonalInfo.Text += name + Environment.NewLine + salary + Environment.NewLine + address + Environment.NewLine + Environment.NewLine;
}
}
That is my code for the class Personal info.
private void btnRun_Click(object sender, EventArgs e)
{
PersonalInfo obj = new PersonalInfo("Mr Tan", 3000, "Blk 123, #12-003 Kepple Rd");
obj.PrintPersonalInfo(txtPersonalinfo);
That is my code for the form.cs So far i can only think of adding new class to add more Info. Now i would like to know how to modify PersonalInfo.cs to add more Info.
Thanks for all you help and have a nice day ahead :)
Perhaps you could consider encapsulating your common properties into a new object, say BasicInfo:
public class BasicInfo
{
public string Name {get; set;}
public float Salary {get; set;}
public string Address {get; set;}
// add more properties when necessary
// e.g. Gender
// public string Gender {get; set;}
}
With that, in the constructor of PersonalInfo class, you can just pass in a BasicInfo object so you don't have to worry about all those properties in the PersonalInfo constructor.
public class PersonalInfo
{
BasicInfo basicInfo;
public PersonalInfo(BasicInfo basicInfo)
{
this.basicInfo = basicInfo;
}
}
You can then keep adding new properties into your BasicInfo class without needing to change PersonalInfo constructor. Hopefully it helps and that's what you are looking for.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
For my Project I have to build a data structure to represent an xml file.
My Idea was to use multiple classes representing the different xml layers.
My problem now is how can I change data in the lowest layer from the uppermost one.
In my code example are three calls 2 work 1 doesn't. Why doesn't the last one work?
Is there another way of organizing the data?
public class option
{
public string optionID;
public void setoptionID(string text)
{
optionID = text;
}
}
public class module
{
public option[] opt = new option[1];
private string moduleID;
public void setmoduleID(string text)
{
moduleID = text;
}
}
public class catalogitem
{
public module[] modul = new module[1];
private string ShortName;
public void setShortName(string text)
{
ShortName = text;
}
}
public class Katalog
{
private catalogitem[] items = new catalogitem[1];
public Katalog()
{
}
public void setcatalogitems()
{
items[0].setShortName("asdf"); //works
catalogitem.modul[0].setmoduleID("5"); //works
items[0].modul[0].setmoduleID("5"); //doesn't work
}
}
For me, none of the three statement work.
You have to initialize the objects itself, not only the array.
items[0] = new catalogitem();
items[0].setShortName("asdf");
items[0].modul[0] = new module();
items[0].modul[0].setmoduleID("5");
But I would also suggest you, to use properties instead of setShortName() / setmoduleID() in your classes and methods for adding and initializing sub items.
Of course it depends on the specification / your intention (that I don't know), but here is a possible way to implement for example
CatalogItem. You can read/write ShortName and enumerate all existing modules. I would take a list, not an array. Modules can be
only added one by one and you can check them before really adding them:
public class CatalogItem
{
private readonly List<Module> mModuls;
public IEnumerable<Module> Moduls
{
get { return mModuls; }
}
public string ShortName { get; set; }
public CatalogItem()
{
mModuls = new List<Module>();
}
public void AddModule(Module module)
{
// Add a check that module is assigned.
mModuls.Add(module);
}
}
Some suggestions
Use properties instead of Set Methods
Write only properties are not good by design
if you need only one object of a type, create the object instead of array with 1 object
follow naming conventions C# Coding Conventions and Naming Guidelines
Your somewhat updated code is below.
public class Option
{
public string OptionID { get; set;}
}
public class Module
{
// if you need only one Option, why not create one public Option object, instead of an Array
public Option Option = new Option();
public string ModuleID { get; set; }
}
public class CatalogItem
{
public Module Module = new Module();
public string ShortName { get; set; }
}
public class Katalog
{
private List<CatalogItem> items = new List<CatalogItem>();
public Katalog()
{
for(int i = 0; i < 10; i++)
items.Add(new CatalogItem());
}
public void SetCatalogItem()
{
foreach(CatalogItem ci in items)
{
ci.ShortName = "asdf";
ci.Module.ModuleID = "5";
}
}
}
Glad to help! Please remember to accept the answer if you found it helpful.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was wondering what your opinion about this would be. I'm trying to convert an xml file to a .net object. It's a xml file from the World of Warcraft armory. Here is an example.
<?xml version="1.0" encoding="UTF-8"?>
<baseStats>
<strength attack="48" base="48" block="-1" effective="58"/>
<agility armor="114" attack="-1" base="47" critHitPercent="4.27" effective="57"/>
<stamina base="70" effective="1186" health="11680" petBonus="-1"/>
<intellect base="198" critHitPercent="10.41" effective="1529" mana="22655" petBonus="-1"/>
<spirit base="190" effective="770" healthRegen="39" manaRegen="503"/>
<armor base="2150" effective="2150" percent="12.37" petBonus="-1"/>
</baseStats>
I've thought of 2 ways to convert this to an object and I'd like to hear your opinion about it. Ill show them.
class BaseStats{
public int StrengthAttack{get;set;}
public int StrengthBase{get;set;}
public int StrengthBlock{get;set;}
...
public int ArmorBase{get;set;}
public int ArmorEffective{get;set;}
...
}
or
class BaseStats{
public Strength Strength{get;set;}
public Armor Armor{get;set;}
public class Strength{
public int Attack{get;set;}
public int Base{get;set;}
public int Block{get;set;}
}
public class Armor{
public int Base{get;set;}
public int Effective{get;set;}
}
}
Do you see what I'm trying here. What would be your opinion about each of those ways. Or can you think of any others?
Classless Design using an Anonymous Type
Here's another way, with .NET 3.5, if you don't want to design an explicit class you can build the object dynamically as an anonymous type; one caveat being the object properties are read-only after being initialized.
Use the XML LINQ classes to query the XML content with.
using System;
using System.IO;
using System.Xml.Linq;
Load up the XML string and query it to create an object.
// 1. Load your string into a document.
XDocument xdoc = XDocument.Load(new StringReader(my_WoW_XML_String));
// 2. Create the anonymous type...
var statsObject = new
{
StrengthInfo = new
{
Attack = int.Parse(xdoc.Element("strength").Element("attack").Value),
Base = int.Parse(xdoc.Element("strength").Element("base").Value),
Block = int.Parse(xdoc.Element("strength").Element("block").Value),
Effective = int.Parse(xdoc.Element("strength").Element("effective").Value),
},
AgilityInfo = new
{
Armor = int.Parse(xdoc.Element("agility").Element("armor").Value),
Attack = int.Parse(xdoc.Element("agility").Element("attack").Value),
Base = int.Parse(xdoc.Element("agility").Element("base").Value),
CritHitPercent = int.Parse(xdoc.Element("agility").Element("critHitPercent").Value),
Effective = int.Parse(xdoc.Element("agility").Element("effective").Value),
}
// Do the same with <spirit> and <armor> elements, etc.
// Include only the properties you want from the XML.
}; // end anonymous object.
Use your anonymous object normally like so:
Console.Write("strength: attack={0}, effective={1}; armor agility={2}",
statsObject.StrengthInfo.Attack,
statsObject.StrengthInfo.Effective,
statsObject.AgilityInfo.Armor);
// Do whatever you want with the object version of WoW stats.
If you have multiple XML files to process with the same schema then just wrap all the above in a loop to process one at a time.
If you have the XSD schema (or can create one), I've used LinqToXsd to create some quick objects. The nice thing about LinqToXsd is that it creates methods you can use to easily parse XML into your objects.
Microsoft has released it as Open Source - and you can simply use a command-line call to pass in your .xsd and it will generate a .cs file with all of your classes.
class CElement
{
public int? attack { get; set; }
public int? base { get; set; }
public int? block { get; set; }
public int? effective { get; set; }
public int? petBonus { get; set; }
public int? mana { get; set; }
public int? healthRegen { get; set; }
public int? manaRegen { get; set; }
public double? critHitPercent { get; set; }
public double? percent { get; set; }
}
class CBaseStats
{
public CElement strength;
public CElement agility;
public CElement stamina;
public CElement intellect;
public CElement spirit;
public CElement armor;
}
If you got complete xml,
1. generate xsd from xml using the xsd.exe tool
2. generate class from the generated xsd using xsd.exe tool
http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx