modify public string with default value in C# - c#

I have an string like "0000000"
and declared it in a class
public class Days_string
{
private string days= "0000000";
public string Days
{
get
{
return days;
}
set
{
days = value;
}
}
}
and I tried to change the string by clicking on 7 buttons
like this:
Days_string daystr = new Days_string();
var aStringBuilder = new StringBuilder(daystr.Days);
aStringBuilder.Remove(5, 1);
aStringBuilder.Insert(5, "1");
daystr.Days = aStringBuilder.ToString();
the output is 0000010
but it changed to 0000000 when I call it again
whats should i do?

Use static variable and static properties instead.and access the properties using className.properties name
public class Days_string
{
private static string days = "0000000";
public static string Days
{
get
{
return days;
}
set
{
days = value;
}
}
}

Even though the code is strange, but to solve your problem, you have at least two options:
Use an static variable :
private static string days = "0000000";
Or, create a global Days_string instance inside your form. By now, you are creating a new Days_string instance behind each button!

Related

Sharing values between different Classes in WPF

I have a WPF Project where I want to save DataRows from a DataGrid into an "options" class and retrieve those variables in another window.
Thats how I save my Variable from my DataGrid into my "options" Class (mainWindow.xaml.cs):
options.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
This Variable im saving via a getter and setter (options.cs):
public string Title
{
get { return title; }
set { title = value; }
}
And now I want to retrieve the saved variable in another window(updateDatabse.xaml):
private void getUpdateEntries()
{
Options returnValues = new Options();
titleBox.Text = returnValues.Title;
}
My Question is: Why is my textbox "titleBox" empty when running my code.
If the logic of your task does not provide for the creation of several instances of classes (and as far as I understand your explanations, this is so), then you can use the Singlton implementation.
Example:
public class Options
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private Options() { }
public static Options Instance { get; } = new Options();
}
Options.Instance.Title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
private void getUpdateEntries()
{
titleBox.Text = Options.Instance.Title;
}
You mixed things up.
private void getUpdateEntries()
{
Options returnValues = new Options();
returnValues.title = Convert.ToString((showEntries.SelectedItem as DataRowView).Row["title"]);
titleBox.Text = returnValues.Title;
}

Why do I not have access to these Properties?

I am having an issue passing properties from one class to another.
I'm getting an error saying that an object reference is required for all of the Game properties in the second class. They are highlighted at the bottom.
this is my first class (Game):
class Game
{
private string verb= "";
private string noun= "";
private string adjective= "";
private string panimal= "";
private string pnoun= "";
public string Verb
{
get {return verb; }
set {verb = value; }
}
public string Noun
{
get {return noun; }
set {noun = value; }
}
public string Adjective
{
get {return adjective;}
set {adjective = value; }
}
public string Panimal
{
get {return panimal; }
set {panimal = value; }
}
public string Pnoun
{
get {return pnoun; }
set {pnoun = value; }
}
public void InScreen()
{
Console.WriteLine("First, give me a past tense VERB: ");
Verb = Console.ReadLine();
Console.WriteLine("\nNow, give me a NOUN: ");
Noun = Console.ReadLine();
Console.WriteLine("\nNext, I will need an ADJECTIVE: ");
Adjective = Console.ReadLine();
Console.WriteLine("\nNow, I will need an ANIMAL(plural): ");
Panimal = Console.ReadLine();
Console.WriteLine("\nFinally, I neeed a plural NOUN: ");
Pnoun = Console.ReadLine();
}
My second class (InsertFunOOUI)
public void Poem()
{
Console.WriteLine("Humpty Dumpty " + **Game.Verb** + "on a " +
**Game.Noun**
);
Console.WriteLine("Humpty Dumpty had a " + **Game.Adjective** + "
fall"
);
}
...you get the picture.
Game is a Type. A class. You need to create an instance of it:
Game g = new Game();
and only then use:
g.Verb
etc.
You need to setup an instance of Game in order to use it, unless it you intended for it to be a static class.
Game game = new Game();
game.InScreen();
Something like that?
First create an instance of your game like #ispiro said. You need to do this once (in the main if possible). Then create an instance of your class poem. Use dependency injection and pass the properties of the game object in as parameters instead of the whole object if possible. I would even create a method inside your Poem class that handles the Console Output. Adapt this code to your liking:
public void main()
{
var game = new Game();
var poem = new Poem();
poem.Output(game.Verb, game.Adjective);
}
public class Poem()
{
public void Output(string verb, string adjective)
{
// your console writeline code
}
}

C# enum in public variable .NET

For my program, I created a new class called FinishedPiece with a number of public variables available to my main program. For example:
class FinishedPiece
{
private double _PieceLength;
public double PieceLength
{
get { return _PieceLength; }
set { _PieceLength = value; }
}
}
This all works fine, because then I can declare a new FinishedPiece and add properties:
FinishedPiece piece = new FinishedPiece();
piece.PieceLength = 48.25;
My question is, how do the same with an enum? If I do
public enum Cut
{
Angle = 0,
Straight = 1,
AngleThenStraight = 2,
StraightThenAngle = 3
};
then I'd like to change it something like this: piece.Cut = Cut.Angle; but I can only change it by declaring a new FinishedPiece.Cut object:
FinishedPiece.Cut cut = new FinishedPiece.Cut();
cut = FinishedPiece.Cut.Angle;
How do I make an enum available inside a variable so I can do piece.Cut = Cut.Angle? To me it would make sense to do something like this, but it doesn't appear to work.
public int Cut
{
get { return _Cut; }
set { _Cut = value; }
}
private enum _Cut
{
Angle = 0,
Straight = 1,
AngleThenStraight = 2,
StraightThenAngle = 3
};
Thanks in advance! Let me know if my question is unclear and I'll try to help as best as I can.
How do I make an enum available inside a variable so I can do
piece.Cut = Cut.Angle?
Just define another property of type Cut in your class like:
public Cut Cut { get; set; }
Then you can do:
FinishedPiece piece = new FinishedPiece();
piece.PieceLength = 48.25;
piece.Cut = Cut.Angle; //like this
So your class would like like:
class FinishedPiece
{
private double _PieceLength;
public double PieceLength
{
get { return _PieceLength; }
set { _PieceLength = value; }
}
public Cut Cut { get; set; }
}
Consider using Auto-Implemented properties, if you have only simple set and get
Like this:
class FinishedPiece
{
private double _PieceLength;
public double PieceLength
{
get { return _PieceLength; }
set { _PieceLength = value; }
}
private Cut _Cut;
public Cut Cut
{
get { return _Cut; }
set { _Cut = value; }
}
}
public enum Cut
{
Angle = 0,
Straight = 1,
AngleThenStraight = 2,
StraightThenAngle = 3
};
Then you can do:
var piece = new FinishedPiece();
piece.Cut = Cut.AngleThenStraight;
You can try this:
private enum Cut
{
//if you dont want to use any of these values as defaults
//just add another value and in your class private member
//assign it like for example a value called None
Angle = 0,
Straight = 1,
AngleThenStraight = 2,
StraightThenAngle = 3
};
public class FinishedPiece
{
//give it a default,if like stated in the enum you dont want
//any of those values create a None and place it here as default.
private Cut cutObj = Cut.Angle;
public Cut CutObj
{
get { return cutObj; }
set { cutObj = value; }
}
}
Then in your calling code...
FinishedPiece piece = new FinishedPiece();
//if you dont want the default change it...
piece.CutObj = Cut.Straight;

How do I retrieve data from a list<> containing class objects

I want to retrieve data from a list I created that contains class objects via a foreach but I'm not able to.
Can somebody please tell me what's missing in my code?
I have a class Recipes.cs that contains the following code:
public class Recipe
{
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
public Recipe(string overskrift, int recipe_id, string opskrift,int kcal)
{
_oveskrift = overskrift;
_recipe_id = recipe_id;
_opskrift = opskrift;
_kcal = kcal;
}
}
public class Recipes
{
public List<Recipe> CreateRecipeList()
{
Recipe opskrift1 = new Recipe("Cornflakes med Chili",1,"4 kg cornflakes bages", 420);
Recipe opskrift2 = new Recipe("Oksemørbrad",2,"Oksemørbrad steges i baconfedt", 680);
Recipe opskrift3 = new Recipe("Tun i vand",3,"Dåsen åbnes og tunen spises", 120);
List<Recipe> Recipelist = new List<Recipe>();
Recipelist.Add(opskrift1);
Recipelist.Add(opskrift2);
Recipelist.Add(opskrift3);
return Recipelist;
}
}
I call CreateRecipeList() from another class calculator.cs and the code looks like this:
private int FindRecipes()
{
List<Recipe> Rlist = new List<Recipe>();
// CREATE THE CLASS AND ADD DATA TO THE LIST
Recipes r = new Recipes();
Rlist = r.CreateRecipeList();
int test = 0; // used only for test purposes
foreach(var rec in Rlist)
{
rec.????
test++;
}
return test;
}
I would presume that I should be able to dot my way into rec."the class object name"."the value"
But nothing happens!.
All I get is the option to rec.Equals, rec.GetHashcod ect. which is clearly wrong.
For the record I have also tried:
foreach(Recipe rec in Rlist)
{
rec.????
test++;
}
But that doesn't work either.
The Int test are only there for test purposes.. and it return 3.. so the list does contain the correct information.
Please show us the code for the Recipe class. Besides that, you're most of the way there...
foreach(Recipe rec in Rlist)
{
string str = rec.<PropertyName>;
}
You need to set the proper access modifiers for the members in your Recipe class.
public : Access is not restricted.
protected : Access is limited to the containing class or types derived from the containing class.
Internal : Access is limited to the current assembly.
protected internal: Access is limited to the current assembly or types derived from the containing class.
private : Access is limited to the containing type.
By default, the members of your Recipe class will have the private access modifier.
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
is:
private string _oveskrift;
private int _recipe_id;
private string _opskrift;
private int _kcal;
Maybe you want to modify your member access as follows, in order to set the values of the members only inside the class code. Any attempt to set their values outside the Recipe class will fail, as the set is private. The get remains public, which makes the value available for reading.
public class Recipe
{
string _oveskrift;
int _recipe_id;
string _opskrift;
int _kcal;
public string Oveskrift
{
get
{
return _oveskrift;
}
private set
{
_oveskrift=value;
}
}
public int RecipeId
{
get
{
return _recipe_id;
}
private set
{
_recipe_id = value;
}
}
public string Opskrift
{
get
{
return _opskrift;
}
private set
{
_opskrift = value;
}
}
public int Kcal
{
get
{
return _kcal;
}
private set
{
_kcal = value;
}
}
public Recipe(string overskrift, int recipe_id, string opskrift, int kcal)
{
_oveskrift = overskrift;
_recipe_id = recipe_id;
_opskrift = opskrift;
_kcal = kcal;
}
}
Also, please read as soon as possible the following MSDN article: Capitalization Conventions. And also, this one: C# Coding Conventions (C# Programming Guide).

Replacing/changing a blank or null string value in C#

I've got something like this in my property/accessor method of a constructor for my program.
using System;
namespace BusinessTrips
{
public class Expense
{
private string paymentMethod;
public Expense()
{
}
public Expense(string pmtMthd)
{
paymentMethod = pmtMthd;
}
//This is where things get problematic
public string PaymentMethod
{
get
{
return paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(" "))
paymentMethod = "~~unspecified~~";
else paymentMethod = value;
}
}
}
}
When a new attribute is entered, for PaymentMethod, which is null or a space, this clearly does not work. Any ideas?
do you perhaps just need to replace string.IsNullOrWhiteSpace(" ") with string.IsNullOrWhiteSpace(value) ?
From your posted code, you need to call:
this.PaymentMethod = pmtMthd;
instead of
paymentMethod = pmtMthd;
The capital p will use your property instead of the string directly. This is why it's a good idea to use this. when accessing class variables. In this case, it's the capital not the this. that makes the difference, but I'd get into the habit of using this.
Jean-Barnard Pellerin's answer is correct.
But here is the full code, which I tested in LinqPad to show that it works.
public class Foo {
private string _paymentMethod = "~~unspecified~~";
public string PaymentMethod
{
get
{
return _paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(value))
_paymentMethod = "~~unspecified~~";
else _paymentMethod = value;
}
}
}
With a main of:
void Main()
{
var f = new Foo();
f.PaymentMethod = "";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = " ";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = "FooBar";
Console.WriteLine(f.PaymentMethod);
}
Output from console:
~~unspecified~~
~~unspecified~~
FooBar

Categories