Getters and Setters, getting multiple fields - c#

public class Teams : INotifyPropertyChanged
{
public string CombinedTeams
{
get
{
return Combined;
}
set
{
{
CombinedTeams += value;
NotifiyPropertyChanged("Combined");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifiyPropertyChanged(string p)
{
if (null != p)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
private string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
set
{
{
Combined += value;
}
}
}
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string HomeScore { get; set; }
public string AwayScore { get; set; }
}
I got a problem, when trying combine my strings together and having one LONG string that contains all the values from when I parse my XML I only get the First set of values,
basically I get
Team1 Score1 : Score2 Team2
as opposed to
Team1 Score1 : Score2 Team2 Team3 Score3 : Score4 Team4 Team5 Score5 : Score6 Team6
I am binding my Control to CombinedTeams
could you guys help me out? I just want to store the previous string and then combine the new string with the old one, I cant see it being hard but this is confusing me and reading up on it makes me more confused...
Thanks,
John

Your code concatenates the new value to an empty string (last = "").
You probably want to concatenate to the previous value.

I'm not sure what you are expecting, last is always initialized to "", so the += is irrelevant.
Seems like the class called Teams is really a game?
And I don't think setting HomeTeam, AwayTeam, HomeScore, AwayScore over and over again (and then saving this internally somehow) is a good way to keep track of multiple games.
Why don't you look at using a collection of games?
Try something like this:
In a GamesLib library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace GamesLib
{
public class Game
{
public string HomeTeam { get; private set; }
public string AwayTeam { get; private set; }
public string HomeScore { get; private set; }
public string AwayScore { get; private set; }
public string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
}
public Game(string HomeTeam, string AwayTeam, string HomeScore, string AwayScore)
{
this.HomeTeam = HomeTeam;
this.HomeScore = HomeScore;
this.AwayTeam = AwayTeam;
this.AwayScore = AwayScore;
}
}
public class Games : List<Game>, INotifyPropertyChanged
{
public string CombinedTeams
{
get
{
var str = "";
foreach (Game g in this)
{
str += g.Combined;
}
return str;
}
}
public new void Add(Game g)
{
base.Add(g);
if ( PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs("CombinedTeams"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
In a console program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GamesLib;
namespace TestHarness
{
class Program
{
static void Main(string[] args)
{
var gs = new GamesLib.Games();
gs.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(gs_PropertyChanged);
var g = new Game("hometeam", "awayteam", "1", "0");
gs.Add(g);
g = new Game("lions", "bears", "1", "0");
gs.Add(g);
Console.WriteLine("Final result:" + gs.CombinedTeams);
}
static void gs_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
var gs = sender as Games;
Console.WriteLine("Changed: " + gs.CombinedTeams);
}
}
}

The reason you are getting the incorrect results is because you have one property referring to another property, and the second property always returns a specific value.
This block of code, when called from elsewhere, will return the results of some other variable called "Combined" which you have defined below...
public string CombinedTeams
{
get
{
return Combined;
}
...
}
private string Combined
{
get
{
return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
...
}
Everything else is academic because you're getter(s) essentially always return " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam.
I suspect you will want to restructure your code to be something more like this
public class Teams : INotifyPropertyChanged
{
private string Combined; // Backing for CombinedTeams
public string CombinedTeams
{
get
{
return Combined;
}
set
{
// This only concatinates values; Combined will get longer each time.
Combined += value;
// ViewModels should always notify after the vale has changed
NotifyOfPropertyChange("CombinedTeams");
}
}
// Adds a new team, assuming HomeTeam, HomeScore, AwayScore, and AwayTeam have been initialized
public void AddTeam()
{
CombinedTeams = " " + HomeTeam + " " + HomeScore + " - " + AwayScore + " " + AwayTeam;
}
}
Certainly there are better ways to do that, but that should get you a start, I hope.
General rule (broken all the time by the code-ninjas, which is fine) is that a Property shouldn't do any calculations of it's own, it's really there to allow public access to private data in the class.
It might be worthwhile to run through a couple of articles on C# Properties. Here are some suggestions to get you started: http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.80).aspx and http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx and of course, some Good Search Results

Related

Trouble with Data Binding properties within custom Pin class using Xamarin Forms

I'm having trouble setting the data binding for some custom properties within a custom Pin class using Xamarin forms.
Here is the two custom classes I'm dealing with.
public class CustomPin : Pin
{
public static readonly BindableProperty NameProperty = BindableProperty.Create("Name", typeof(string), typeof(Pin), default(string));
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public string Icon { get; set; }
}
public class UserData
{
public string Callsign { get; set; }
public string ID { get; set; }
public string Team { get; set; }
public CustomPin Pin { get; set; }
public Position Position { get; set; }
}
Here is the element that holds the values of my Bindings.
public static UserData myUserData = new UserData
{
Callsign = "User",
Pin = new CustomPin
{
BindingContext = myUserData,
Position = new Position(),
Name = "",
Label = ""
},
Position = new Position(),
};
Here is how I set the bindings
myUserData.Pin.SetBinding(CustomPin.PositionProperty, "Position");
myUserData.Pin.SetBinding(CustomPin.LabelProperty, "Callsign");
myUserData.Pin.SetBinding(CustomPin.NameProperty, "Callsign");
And there is the method I use to debug
Debug.WriteLine
(
myUserData.Pin.Name + " should be " + myUserData.Callsign + "\n" +
myUserData.Pin.Label + " should be " + myUserData.Callsign + "\n" +
myUserData.Pin.Position.Latitude + " should be " + myUserData.Position.Latitude + "\n" +
myUserData.Pin.Position.Longitude + " should be " + myUserData.Position.Longitude + "\n"
);
Here is the output, as you can see it doesn't apply the bindings - however I do use this bindings in other objects (such as Xamarin.Forms.Label) and they work just fine.
should be User
should be User
0 should be 37.63150086
0 should be -122.43626643
Thank you in advance for any help.

C# Iterate through nested properties using IEnumerator

I have seen examples (and official ones) for IEnumerator on lists and arrays or dicts, but I have a different problem. I have classes with properties, how may I implement the IEnumerable and IEnumerator in that case?
My properties classes are:
public class standardMessage
{
public messageProperties message { get; set; }
public messageFlag flag { get; set; }
}
public class messageProperties
{
public string messageSubject { get; set; }
public string messageBody { get; set; }
}
public class messageFlag
{
public Boolean flagImportant { get; set; }
public Boolean flagPersonal { get; set; }
}
And this is the Program:
public class Program
{
static void Main(string[] args)
{
standardMessage myMessage = new standardMessage();
myMessage.message = new messageProperties
{
messageSubject = "Greetings",
messageBody = "Happy Weekend"
};
myMessage.flag = new messageFlag
{
flagImportant = false,
flagPersonal = true
};
//how do I iterate through all properties, without knowing how many are there, instead of writing this worm line of code?
Console.WriteLine(myMessage.message.messageSubject.ToString() + "\r\n" + myMessage.message.messageBody.ToString() + "\r\n" + myMessage.flag.flagImportant.ToString() + "\r\n" + myMessage.flag.flagPersonal.ToString());
Console.ReadLine();
}
}
If you want a production-grade way of printing your objects as a formatted string, you need to go and override ToString in all your classes to return whatever format you want.
However, if you just want to print the things on screen for debugging or logging purposes, why not JSON?
public static string ToJson(object #object) =>
System.Text.Json.JsonSerializer.Serialize(#object, new JsonSerializerOptions{WriteIndented = true});
Console.WriteLine(ToJson(myMessage));
Prints
{
"message": {
"messageSubject": "Greetings",
"messageBody": "Happy Weekend"
},
"flag": {
"flagImportant": false,
"flagPersonal": true
}
}
Quick and dirty, but quick and working.
I made a very primitive object to json converter. I wouldn't use this in production and it's about 30% slower than Newtonsoft but it get's the job done.
private static string PrintObject(object obj, int depth = 1)
{
var type = obj.GetType();
if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String))
return "\"" + obj.ToString() + "\"";
var props = type.GetProperties();
string ret = "";
for (var i = 0; i < props.Length; i++)
{
var val = props[i].GetValue(obj);
ret += new string('\t', depth) + "\"" + props[i].Name + "\":" + PrintObject(val, depth + 1);
if (i != props.Length - 1)
ret += "," + Environment.NewLine;
}
return ("{" + Environment.NewLine + ret + Environment.NewLine + new string('\t', depth - 1) + "}").Replace("\t", " ");
}
Gives the result
{
"message":{
"messageSubject":"Greetings",
"messageBody":"Happy Weekend"
},
"flag":{
"flagImportant":"False",
"flagPersonal":"True"
}
}

How do I populate a string array upon instantiation?

So I have created a class that holds properties for the names of albums, including their genre, name and artist with an array that will hold the track list. When compiled, the properties' default values are replaced however I don't know how to replace the default values for the array - I don't know how to replace the default track listing with new tracks for each album. Thanks.
Here is the CD.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_2
{
class Cd
{
string name;
string artist;
string genre;
public string[] tracklist;
public string[] newTracklist;
public string getName()
{
return name;
}
public void setName(string newName)
{
name = newName;
}
public string getArtist()
{
return artist;
}
public void setArtist(string newArtist)
{
artist = newArtist;
}
public string getGenre()
{
return genre;
}
public void setGenre(string newGenre)
{
genre = newGenre;
}
public string[] getTracklist()
{
return tracklist;
}
public void setTracklist(string[] newTracklist)
{
string[] tracklist = newTracklist;
}
public Cd()
{
this.name = "CD Name";
this.artist = "CD Artist";
this.genre = "CD Genre";
this.tracklist = new string[3] { "Track1", "Track2", "Track3" };
this.newTracklist = new string[3] { "newTrack1", "newTrack2", "newTrack3" };
}
}
}
And here is the main.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_2
{
class Exercise2
{
static void Main()
{
Cd CD1 = new Cd();
CD1.setName("Kill 'Em All");
CD1.setArtist("Metallica");
CD1.setGenre("Thrash Metal");
Cd CD2 = new Cd();
CD2.setName("Ride The Lightning");
CD2.setArtist("Metallica");
CD2.setGenre("Thrash Metal");
Cd CD3 = new Cd();
CD3.setName("Master Of Puppets");
CD3.setArtist("Metallica");
CD3.setGenre("Thrash Metal");
Console.WriteLine(CD1.getName() + " - " + CD1.getArtist() + " - " + CD1.getGenre() + " - " + CD1.getTracklist());
Console.WriteLine(CD2.getName() + " - " + CD2.getArtist() + " - " + CD2.getGenre());
Console.WriteLine(CD3.getName() + " - " + CD3.getArtist() + " - " + CD3.getGenre());
}
}
}
The problem is your setTracklist method creates a new array every time:
public void setTracklist(string[] newTracklist)
{
string[] tracklist = newTracklist;
}
Instead, you need to set the instance tracklist member:
public void setTracklist(string[] newTracklist)
{
tracklist = newTracklist;
}
One more piece of advice. Don't create methods to get and set properties, it's just unnecessary work. Change:
string name;
string artist;
string genre;
public string[] tracklist;
public string[] newTracklist;
To:
public string Name {get; set;}
public string Artist {get; set;}
public string Genre {get; set;}
public string[] Tracklist {get; set;}
You also might want to change tracklist to a List<String> so you can easily add tracks:
public List<String> Tracklist {get; set;}
If you do this, you can create a Cd instance a lot easier:
var newCD = new Cd
{
Name = "Kill 'Em All",
Artist = "Metallica",
Genre = "Thrash Metal"
};
newCD.Tracklist.Add("Hit the Lights");
newCD.Tracklist.Add("The Four Horsemen");
newCD.Tracklist.Add("Motorbreath");
// etc etc
Update:
Here's the full code, in case something got mixed up. I've also implemented a getTracklist method which returns all the tracks is a comma delimited form.
using System;
using System.Collections.Generic;
class Cd
{
public string Name { get; set; }
public string Artist { get; set; }
public string Genre { get; set; }
public List<string> Tracklist { get; set; }
public Cd()
{
Name = "CD Name";
Artist = "CD Artist";
Genre = "CD Genre";
Tracklist = new List<string>();
}
public string getTracklist()
{
return String.Join(", ", Tracklist);
}
}
public class Exercise2
{
public static void Main()
{
Cd CD1 = new Cd();
CD1.Name = "Kill 'Em All";
CD1.Artist = "Metallica";
CD1.Genre = "Thrash Metal";
CD1.Tracklist.Add("Hit the Lights");
CD1.Tracklist.Add("The Four Horsemen");
CD1.Tracklist.Add("Motorbreath");
Cd CD2 = new Cd();
CD2.Name = "Ride The Lightning";
CD2.Artist = "Metallica";
CD2.Genre = "Thrash Metal";
Cd CD3 = new Cd();
CD3.Name = "Master Of Puppets";
CD3.Artist = "Metallica";
CD3.Genre = "Thrash Metal";
Console.WriteLine(CD1.Name + " - " + CD1.Artist + " - " + CD1.Genre + " - " + CD1.getTracklist());
Console.WriteLine(CD2.Name + " - " + CD2.Artist + " - " + CD2.Genre);
Console.WriteLine(CD3.Name + " - " + CD3.Artist + " - " + CD3.Genre);
}
}
You would just write
CD1.setTrackList(new string[] {"Hit The Lights", "The Four Horsemen", "Motorbreath"});
And your setTrackList should read:
public void setTracklist(string[] newTracklist)
{
tracklist = newTracklist;
}
The way you originally wrote it, you were creating a new array of tracks each time you were setting it, instead of setting the backing property.
However, there is a better way to do this. C# has what's called Auto Properties. They handle all this for you.
public string Name {get; set;}
public string Artist {get; set;}
//.... etc

String.ToString() method on null String Object

I have the following code:
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
var obj=(person)Activator.CreateInstance(typeof(person));
Console.WriteLine(obj);
}
}
public class person
{
public int id { get; set; }
public string name { get; set; }
public DateTime dob { get; set; }
public override string ToString()
{
return id.ToString() + " " + name + " " + dob.ToString();
}
}
}
which yields the following output:
0 1/1/0001 12:00:00 AM
However, if change the person.ToString() to the following:
public override string ToString()
{
return id.ToString() + " " + name.ToString() + " " + dob.ToString();
}
I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
at Rextester.person.ToString()
Can someone shed some light on it.
Edited
I'm guessing your code samples aren't correct as it stands in your question and you're actually seeing this behavior:
return id.ToString() + " " + name + " " + dob.ToString();
works
return id.ToString() + " " + name.ToString() + " " + dob.ToString();
doesn't work
This is because adding a null value to a string is legal but calling a method on a null instance is not.
See this question:
Why is adding null to a string legal?

"The name 'modToSend' does not exist in the current context"

I have this simple piece of coding in my Homecontroller.cs, but I receive the error message on the last line, saying "The name 'modToSend' does not exist in the current context". How is that possible? Only in the last line is it not known????
public class HomeController : Controller, IDisposable
{
private MvcEShop2.WcfEshop2Service.Eshop2ServiceClient proxy = null;
private String GetDuration(DateTime startdatum, DateTime einddatum)
{
String maand1 = startdatum.Month.ToString("MMMM");
String maand2 = einddatum.Month.ToString("MMMM");
String duration = "";
if (maand1 == maand2)
{
duration = startdatum.Day.ToString()
+ " - " + einddatum.Day.ToString()
+ " " + maand1
+ " " + startdatum.Year.ToString();
}
else
{
duration = startdatum.Day.ToString()
+ startdatum.Month.ToString("MMMM")
+ " - " + einddatum.Day.ToString()
+ " " + einddatum.Month.ToString("MMMM")
+ " " + startdatum.Year.ToString();
}
return duration;
}
public HomeController()
{
proxy = new MvcEShop2.WcfEshop2Service.Eshop2ServiceClient();
}
struct EventStruct
{
public SEvent Event { get; set; }
public String Duration { get; set; }
};
public ActionResult Index()
{
List<SEvent> modFromWcf = proxy.GetAllEventsByPeriod(#System.DateTime.Now.Year, #System.DateTime.Now.Year + 1, "EN").ToList();
List<EventStruct> modTosend = new List<EventStruct>();
foreach (SEvent item in modFromWcf)
{
EventStruct ES;
ES.Event = item;
ES.Duration = GetDuration(item.StartDate ,item.EndDate);
modTosend.Add(ES);
};
return View("Index", modToSend);
}
}
If that's a direct copy & paste from your code, check the case of the 'S' in your parameter to the View being returned.

Categories