C# Iterate through nested properties using IEnumerator - c#

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

Related

How to WriteLine all properties stored in a list with C#?

I have a mini assignment where I have to review the fundamentals of classes and properties. In the context of this code, I am trying to figure out how to print all the properties for each task that is stored in a list.
Here is the code. The commented out code is what I tried so far to print all the properties for each task stored in TaskList.
namespace FunProject
{
internal class Program
{
static void Main(string[] args)
{
var person1 = new Person
{
FirstName = "Mister",
LastName = "Programmer",
Age = 26
};
Console.WriteLine(person1.FullName());
var Task1 = new Task
{
TaskName = "read",
Description = "gain knowledge",
Id = 1,
IsDone = true
};
var Task2 = new Task
{
TaskName = "eat",
Description = "gain sustenance",
Id = 2,
IsDone = false
};
person1.TaskList = new List<Task>();
person1.TaskList.Add(Task1);
person1.TaskList.Add(Task2);
//Person1.TaskList.ForEach(i => Console.Write("{0}\t", i));
//Person1.TaskList.ForEach (x => Console.WriteLine(x));
//Console.WriteLine(String.Join("{0}\t", Person1.TaskList.ToString()));
//foreach (Task t in Person1.TaskList)
//{
// Console.WriteLine(t);
//}
Console.Read();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set;}
public int Age { get; set; }
public List<Task>TaskList { get; set; }
public string FullName()
{
return ($"{FirstName} {LastName}");
}
}
public class Task
{
public int Id { get; set; }
public string TaskName { get; set;}
public string Description { get; set; }
public bool ?IsDone { get; set;}
}
}
Output should be something like:
Mister Programmer
Current Tasks:
TaskName: read
TaskDescription: gain knowledge
Id: 1
IsDone: true
TaskName: eat
TaskDescription: gain sustenance
Id: 2
IsDone: false
If you want to resolve this problem what I would do first, I will create task list something like this:
var list = new List<Task>();
list.Add(Task1);
list.Add(Task2);
And then I will add this list to the person that you are creating
var person1 = new Person
{
FirstName = "Mister",
LastName = "Programmer",
Age = 26,
TaskList = list
};
So now you have a person with the list of the tasks. Which is everything you need to create for the output.
So for the output you will need to format something like this:
Console.WriteLine(person1.FirstName + " " + person1.LastName);
Console.WriteLine("Current Tasks:");
person1.TaskList.ForEach(x => Console.WriteLine("TaskName:" + " " +
x.TaskName + "\n" + "TaskDescription:" + " " + x.Description + "\n" + "Id:" + " " + x.Id + "\n" + "IsDone:" + " " + x.IsDone.ToString().ToLower()));
Console.Read();
But if you want to have the properties names without writing the properties in the Console.WriteLine("TaskDescription") or etc. and also to get the values for each property from person object, you will need to use System.Reflection:
Type t = person1.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo prop in properties)
{
if (!prop.Name.Equals("TaskList"))
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(person1)}");
}
else
{
foreach (var t1 in person1.TaskList)
{
foreach (var propTask in t1.GetType().GetProperties())
{
Console.WriteLine($"{propTask.Name}: {propTask.GetValue(t1, null).ToString().ToLower()}");
}
Console.WriteLine("\n");
}
}
}
I would use System.Reflection for this...
foreach (var t in person1.TaskList)
{
foreach (var prop in t.GetType().GetProperties())
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(t, null).ToString()}");
}
Console.WriteLine("\n");
}

How to parse this JSON string into 2 List<String>

I have some problem to understand how you parse this JSON string.
As seen we have 2 lists in the JSON string. "bids" and "asks"
For bids for example we have:
0.035314,25.986
0.035313,6.947
etc
The goals is to create 2 lists, bids and asks where each element in the list contains the above. For example each index contains this information then: "0.035314,25.986" etc.
How will one approach this string when doing this?
Expected output should be as an understanding like below:
List<String> bidsLIST = new List<String>();
List<String> asksLIST = new List<String>();
bidsLIST.Add("0.035314,25.986");
bidsLIST.Add("0.035313,6.947");
asksLIST .Add("0.035319,1.139");
asksLIST .Add("0.03532,28.381");
JSON is located here:
https://pastebin.com/j6Xckh49
{"bids":[[0.035314,25.986],[0.035313,6.947],[0.035312,17.441],[0.035308,4],[0.0353,6.188]],"asks":[[0.035319,1.139],[0.03532,28.381],[0.035324,6.7],[0.035329,2.307],[0.03533,6.868]],"nonce":451939443}
This code is not entirely correct:
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
void testparseJSON()
{
String responseBody = "{" +
'"' + "bids" + '"' + ":[[0.035314,25.986],[0.035313,6.947],[0.035312,17.441],[0.035308,4],[0.0353,6.188]]," +
'"' + "asks" + '"' + ":[[0.035319,1.139],[0.03532,28.381],[0.035324,6.7],[0.035329,2.307],[0.03533,6.868]]," +
'"' + "nonce" + '"' + ":451939443}";
var deserializedTickers = JsonConvert.DeserializeObject<Dictionary<List<String>, bidsasks>>(responseBody);
foreach (var bidsasks in deserializedTickers)
{
var Bids = bidsasks.Value.bids;
var Asks = bidsasks.Value.asks;
if (Bids != null && Asks != null)
{
//How to get the 2 lists here?
}
}
}
public class bidsasks
{
public List<String> bids { get; set; }
public List<String> asks { get; set; }
}
You need an intermediate class to reflect the JSON structure:
public class JsonBidsAsks {
public List<List<string>> bids { get; set; }
public List<List<string>> asks { get; set; }
}
Then you can parse the JSON and convert to the desired structure:
var deserializedTicker = JsonConvert.DeserializeObject<JsonBidsAsks>(responseBody);
var ans = new bidsasks {
bids = deserializedTicker.bids.Select(ba => ba.Join(",")).ToList(),
asks = deserializedTicker.asks.Select(aa => aa.Join(",")).ToList(),
};
void testparseJSON(){
String responseBody = "{" +
'"' + "bids" + '"' + ":[[0.035314,25.986],[0.035313,6.947],[0.035312,17.441],[0.035308,4],[0.0353,6.188]]," +
'"' + "asks" + '"' + ":[[0.035319,1.139],[0.03532,28.381],[0.035324,6.7],[0.035329,2.307],[0.03533,6.868]]," +
'"' + "nonce" + '"' + ":451939443}";
var jsnAsObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(responseBody);
var bids = jsnAsObj.bids;
var asks = jsnAsObj.asks;
}
and put at another class (recommended at a new *.cs file) your DM.
this is just a suggestion and not a must, the code can work as an inner class inside of your current one, but it's not recommended.
public class Rootobject
{
public float[][] bids { get; set; }
public float[][] asks { get; set; }
public int nonce { get; set; }
}
You can deserialize your json to anonymous type:
var template = new
{
bids = new[]
{
new[] {1.0, 1.0}
},
asks = new[]
{
new[] {1.0, 1.0}
},
};
var parsedJson = JsonConvert.DeserializeAnonymousType(responseBody, template);
Now just join bids and asks in two lists:
var bidsLIST = parsedJson.bids.Select(b => string.Join(",", b)).ToList();
var asksLIST = parsedJson.asks.Select(a => string.Join(",", a)).ToList();
After checking the #NetMage answer, I manipulated a little that code and Works without problems.
public class bidsasks
{
public List<List<string>> bids { get; set; }
public List<List<string>> asks { get; set; }
public int nonce { get; set; }
}
public static void testparseJSON()
{
String responseBody = "{" +
'"' + "bids" + '"' + ":[[0.035314,25.986],[0.035313,6.947],[0.035312,17.441],[0.035308,4],[0.0353,6.188]]," +
'"' + "asks" + '"' + ":[[0.035319,1.139],[0.03532,28.381],[0.035324,6.7],[0.035329,2.307],[0.03533,6.868]]," +
'"' + "nonce" + '"' + ":451939443}";
var deserializedTicker = JsonConvert.DeserializeObject<bidsasks>(responseBody);
var ans = new bidsasks
{
bids = deserializedTicker.bids,
asks = deserializedTicker.asks
};
for (int i = 0; i < ans.bids.Count; i++)
{
Console.WriteLine(String.Format("PRICE", ans.bids[i][0]));
Console.WriteLine(String.Format("QTY", ans.bids[i][1]));
}
for (int i = 0; i < ans.asks.Count; i++)
{
Console.WriteLine(String.Format("PRICE", ans.asks[i][0]));
Console.WriteLine(String.Format("QTY", ans.asks[i][1]));
}
}
}

Reading Generic Value from List of Generic Objects

I am trying to loop through a list of generic objects call Condition<T> to read the generic field Value. I followed this question to be able to store the List<Condition<T>>. The issue I am running into now is that I can't use the Value field in my loop. What do I need to change in order to use the Value field?
Main
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal))
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual))
foreach (ConditionBase c in Conditions)
{
if (c.GetType() == typeof(string))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
else if (c.GetType() == typeof(DateTime))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " " + Helpers.FormatDate(c.Value) + " and ";
}
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
Solution
This solution is based on the comments by #orhtej2 & the answer by #Igor.
Main - Test
static void Main(string[] args)
{
var x1 = new Condition<int>(new Field(), 123, ConditionOperator.Equal);
var x2 = new Condition<string>(new Field(), "test", ConditionOperator.Equal);
var x3 = new Condition<DateTime>(new Field(), new DateTime(2018,5,5), ConditionOperator.Equal);
var qqq = new List<ConditionBase>();
qqq.Add(x1);
qqq.Add(x2);
qqq.Add(x3);
foreach (ConditionBase c in qqq)
{
Console.WriteLine(c.GetValue());
}
Console.ReadLine();
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
string GetValue();
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
public string GetValue()
{
if (Value is string)
{
return "'" + Value.ToString() + "'";
}
else if (Value is DateTime)
{
return Helpers.FormatDate(Convert.ToDateTime(Value));
}
else
{
return Value.ToString();
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
You have syntax errors in the code like the lacking public scope of your enums and ConditionOperator.Equal (not ConditionOperator.Equals) but that asside here is the fix.
Conditions should be of type List<ConditionBase>
Use OfType on the List to retrieve and cast the resulting type to Condition<string>. I assume that this was your intention with your added check c.GetType() == typeof(string)
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions.OfType<Condition<string>>())
{
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
If you want a generic property that you can access on all instances regardless of the generic type constraint then you would need to extend the base interface accordingly.
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
object FieldValue { get; }
}
public class Condition<T> : ConditionBase
{
/* I only included the added code in this type */
public object FieldValue
{
get { return (object) this.Value; }
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.FieldValue + "' and ";
}
It seems you want to output your value to a string based on the changes in your question. Add a string formatter to your type.
/* I only included the added code in this type */
public class Condition<T> : ConditionBase
{
private Func<T, string> _formatValue;
public Condition(Field field, T value, ConditionOperator condition, Func<T, string> formatValue)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
this._formatValue = formatValue;
}
public override string ToString()
{
return this._formatValue(this.Value);
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal, (val)=> val.ToString()));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual, (val)=> val));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.ToString() + "' and ";
}

concating string with comma to join a long string

I am getting a List of below class.
public class SmsResponse
{
public string AliasName { get; set; }
public string CellPhoneNumber { get; set; }
public int Response { get; set; }
}
I am passing this list to a function to check if the response field has response other than 0 , if it have than it is a error for which i have to prepare a status string by this method PrepareStatusString();.
bool isSuccess = EvaluateSmsResponse(responseList); //list of smsresponse class
private bool EvaluateSmsResponse(List<SmsResponse> smsResponseList)
{
bool isSent = smsResponseList.Exists(response => response.Response != 0);
if (!isSent)
PrepareStatusString(smsResponseList);
return isSent;
}
private void PrepareStatusString(List<SmsResponse> responseList)
{
bool isfirst = true;
foreach (var item in responseList)
{
if (item.Response != 0)
{
if(isfirst)
StatusDescription += item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString();
else
StatusDescription += "," + item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString();
isfirst = false;
}
}
}
The code is working as desired, but can it be optimized/improved in any way. I am feeling there is a scope improvement but not able to figure out ??
If you're using .NET 4 or newer, you can override SmsResponse.ToString() and then use String.Join<T>(String, IEnumerable<T>) to concatenate the responses.
So your SmsResponse class may look something like this:
public class SmsResponse
{
public string AliasName { get; set; }
public string CellPhoneNumber { get; set; }
public int Response { get; set; }
public override string ToString()
{
return AliasName + "|" + CellPhoneNumber + "|" +
Response.ToString();
}
}
And PrepareStatusString would be:
private void PrepareStatusString(List<SmsResponse> responseList)
{
StatusDescription = string.Join(",", responseList.Where(i => i.Response != 0));
}
StringBuilder will be more efficient at appending strings within the foreach loop (depending on num of iterations)
private void PrepareStatusString(List<SmsResponse> responseList)
{
bool isfirst = true;
StringBulder sb = new StringBuilder();
foreach (var item in responseList)
{
if (item.Response != 0)
{
if(isfirst)
sb.AppendFormat("{0}|{1}|{2}", item.AliasName, item.CellPhoneNumber,item.Response.ToString());
else
sb.AppendFormat(",{0}|{1}|{2}", item.AliasName, item.CellPhoneNumber, item.Response.ToString());
isfirst = false;
}
}
StatusDescription = sb.ToString();
}
I don't know about optimization, but it could be rewritten more expressively as follows:
private void PrepareStatusString(List<SmsResponse> responseList)
{
StatusDescription = responseList
.Where(x => x.Response != 0)
.Select(x => x.AliasName
+ "|" + x.CellPhoneNumber
+ "|" + x.Response.ToString())
.Aggregate((x, y) => x + "," + y);
}
Note that StringBuilder will only offer a noticeable performance benefit if you expect more than a couple hundred objects there.
Use string.Join like so
List<string> elements = new List<string>();
foreach (var item in responseList)
{
if (item.Response != 0)
{
elements.add(item.AliasName + "|" + item.CellPhoneNumber + "|" + item.Response.ToString());
}
}
string result = string.Join(",", elements.ToArray());

Getters and Setters, getting multiple fields

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

Categories