What is the proper syntax to obtain a dictionary key value pair when using trace points?
With a property like the following
public Dictionary<string, decimal> SomeDictionary { get; set; }
I am trying to set a break point with actions on the setter method to trace all incoming values. I've tried the following but none of them work.
{value} 'this gives me a count of how many items are in the dictionary
{value.Value} 'throws an exception, 'Value' doesn't exist
{value[Value]} 'the name 'Value' does not exist in the current context
Based on your SomeDictionary:
public class Example
{
public Dictionary<string, decimal> SomeDictionary { get; set; }
public Example()
{
SomeDictionary = new Dictionary<string, decimal>();
string key = "key";
SomeDictionary[key] = 10.0M;
}
}
static void Main(string[] args)
{
var example = new Example();
Console.ReadKey();
}
If we put a tracepoint at the end of the constructor after the dictionary is defined and the key is added - Tracepoint action:
SomeDictionary: {SomeDictionary}; SomeDictionary[key]: {SomeDictionary[key]}
We can inspect the dictionary - Output:
SomeDictionary: Count = 1; SomeDictionary[key]: 10.0
You can reference the dictionary by using
{ map["key1"] }
or using variable to access the keyvalue pair.
Related
I've got a static class with static getters.
public static class Cars
{
public static KeyValuePair<Guid, string> Acura
{
get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41001"), "Acura"); }
}
public static KeyValuePair<Guid, string> AlfaRomeo
{
get { return new KeyValuePair<Guid, string>(new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41002"), "Alfa Romeo"); }
}
// etc.
}
I need to retrieve all the static properties from this static class and do something with each KeyValuePair. But the following throws a System.FormatException at runtime saying that it could not find recognizable digits
Type type = typeof(Cars);
foreach(var manufacturer in type.GetProperties())
{
if(manufacturer.PropertyType == typeof(KeyValuePair<Guid, string>))
{
var v = manufacturer.GetValue(null, null); //this does not work
// How to get the KeyValuePair<Guid, string>?
}
}
How to get each KeyValuePair?
UPDATE: Sorry.. the solution works perfectly, the problem is that GUID are not valuid Guids.. M is not hexadecimal character
This does not have to do anything with reflection or static properties. Within the getters of your properties there are exceptions thrown.
"MMMMMMMM-509B-477A-ADB1-5CD014B41001" and "MMMMMMMM-509B-477A-ADB1-5CD014B41002" are no valid Guids. Create Guids with valid values and the properties won't throw the exceptions.
Each of the digits in a Guid must be a hexadecimal digit (see here).
new Guid("MMMMMMMM-509B-477A-ADB1-5CD014B41001")
will throw the exception, while for example
new Guid("00000000-509B-477A-ADB1-5CD014B41001")
won't.
I fall in a weird situation, so essentially I need to create a Dictionary with a string as Key and a custom object as Value. The Dictionary have this implementation:
public static Dictionary<string, ForecastType> FullTime
{
get
{
return new Dictionary<string, ForecastType>()
{
{ "1", new ForecastType { Type = SignType.PartialFinal, Sign = Signs.HomeHomePF } },
...
}
}
}
as you can see the key is 1 and the value is a custom class called ForecastType:
public class ForecastType : ViewModel
{
private double _value;
public double Value
{
get { return _value; }
set
{
_value = value;
OnPropertyChanged();
}
}
public Signs Sign { get; set; }
public SignType Type { get; set; }
}
the property Sign and Type don't need an explaination, it's only an implementation of an Enum.
The property Value instead, cause me a lot of headache. In particular I can't set the value to this property, each value that I assign I get 0.
I also implemented the ViewModel, I though to an issue related on PropertyChanged, but even this hasn't fixed the situation.
I valorize the Value property in this way:
FullTime["1"].Value = 5;
Note that the OnPropertyChanged() is called correctly, and the value inside it is 5, but when I set a breakpoint, later the FullTime["1"].. line I get as .Value "0".
What am I doing wrong?
Thanks for any help. Best regards.
The problem is in the FullTime property itself. It always returns a new dictionary:
get
{
return new Dictionary<string, ForecastType>() {...};
}
Every time you call it, whether to set or get anything in that dictionary, you're always getting a brand new dictionary. No dictionary is ever persisted in memory.
Save an instance in the class and return that instance instead. Perhaps something like this:
private static Dictionary<string, ForecastType> _myDict;
public static Dictionary<string, ForecastType> FullTime
{
get
{
if (_myDict == null)
_myDict = new Dictionary<string, ForecastType>() {...};
return _myDict;
}
}
This way it will be initialized the first time you call that property, and any subsequent calls to that property will yield the previously initialized dictionary.
Instead of having the getter for the FullTime property return a new dictionary, you can, as of C# 6, provide a default value for the property like so:
public static Dictionary<string, ForecastType> FullTime {get;} = new Dictionary<string, ForecastType> () { /* initial dictionary values go here */ };
Your FullTime has only a getter, which whenever is called returns a new dictionary with the default value of ForecastType.Value. One possible solution it would be the following:
public static Dictionary<string, ForecastType> FullTime { get; } =
new Dictionary<string, ForecastType>
{
{ "1", new ForecastType
{
Type = SignType.PartialFinal,
Sign = Signs.HomeHomePF
}
// ...
};
The difference is that now you have create a property with only a getter but with a default value, which cannot be changed. This value is a reference to a dictionary Dictionary<string, ForecastType>. Whenever you read the value of this property you would get the same reference but now you could mutate the state of the object that this reference points to, by adding new items to the dictionary, changing values etc.
In Unity3D I am trying to loop through all the components on an object and get their variables and values. This is the code that keeps throwing the exception:
componentvariables = new ComponentVars[component.GetType().GetFields().Length];
int x = 0;
//Get all variables in component
foreach(FieldInfo f in component.GetType().GetFields()){
componentvariables[x]=new ComponentVars();
componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());
x++;
}
The ComponentVars class is
public class ComponentVars{
public Dictionary<string, string> Vars{get;set;}
}
Yes I know it is very simple and I could just use an array of dictionaries but I plan on adding more to it later.
The part that keeps throwing the error is
componentvariables[x].Vars.Add(f.Name,f.GetValue(component).ToString());
I usually see these where a variable is not initialized but I have tried initializing it (as seen in the code above) and I still continue to get a NullRefEx.
Can anyone see what I am doing wrong here?
Make sure you initialize your Vars dictionary before you try to add a value to it:
foreach(FieldInfo f in component.GetType().GetFields()){
componentvariables[x] = new ComponentVars();
componentvariables[x].Vars = new Dictionary<string, string>();
componentvariables[x].Vars.Add(f.Name, f.GetValue(component).ToString());
x++;
}
Or even better, initialize it in the class:
public class ComponentVars{
public Dictionary<string, string> Vars { get; private set; }
public ComponentVars()
{
this.Vars = new Dictionary<string, string>();
}
}
I've a problem with updating a dictionary
I also have read many topics about this saying all the same (e.g. Link)
ExampleDict[key] = value;
I was trying this to my own code:
Model:
public Dictionary<int, string> Info { get; set; }
public Dictionary<int, string> GetInfo(int id)
{
Info = new Dictionary<int, string>();
var game = db.Games.Find(id);
var playerOne = db.Players.Find(game.PlayerOneId);
var playerTwo = db.Players.Find(game.PlayerTwoId);
var PlayerOneName = playerOne.Nickname;
var PlayerTwoName = playerTwo.Nickname;
int scoreOne = CountScorePlayerOne();
int scoreTwo = CountScorePlayerTwo();
// old aproach:
Info.Add(scoreOne, PlayerOneName);
Info.Add(scoreTwo, PlayerTwoName);
//new approach
Info[key] = scoreOne;
return Info;
}
Error
The name 'key' does not exist in the current context
Note: I'm a student and this is for a school project.
Any ideas on what I am doing wrong?
Solved through the code sample from Jon Senchyna, Thank you!
It appears that you are never declaring the variable key. You probably did not mean to use "key" in the "new approach" line.
In addition, I believe your Dictionary is backwards, as it looks like the player name should be the key, not their score. The way you are currently declaring it (Dictionary<int, string>), you are creating a dictionary whose keys are int (score?) and whose values are string (name?).
Here are my suggested edits:
// Corrected dictionary definitions
public Dictionary<string, int> Info { get; set; }
public Dictionary<string, int> GetInfo(int id)
{
// You may want to use a local variable here instead
Info = new Dictionary<string, int>();
...
Info[PlayerOneName] = scoreOne;
Info[PlayerTwoName] = scoreTwo;
return Info;
}
Here are some useful links for learning more about using the Dictionary class (and C# in general if you browse around a bit):
MSDN
DotNetPearls
In the example link in your question there's the method:
public static void SafeDictionaryAdd(Dictionary<string, object> dict, string key, object view)
Which has a string key as an argument. You need to define that key, too.
I'm trying to change a control property from a dictionary so basically the key in the dictionary is the property name of that control and the value will be the property value. is there anyway to do this ?
for example in my dictionary I have "Name" as the key and "buttonSave" as the value, how can I relate them to my control to set its property based on the key and value ?
thanks in advance.
Example for you how to use Reflection in your case with method PropertyInfo.SetValue
public class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
var dictionary = new Dictionary<string, object>
{
{"Id", new Guid()},
{"Name", "Phil"},
{"Phone", "12345678"}
};
var customer = new Customer();
foreach (var pair in dictionary)
{
var propertyInfo = typeof(Customer).GetProperty(pair.Key);
propertyInfo.SetValue(customer, pair.Value, null);
}
using System.Reflection;
look up in MSDN
myControl.GetProperty("Name").SetValue(myControl, "buttonSave", null);
It would also be good idea to check first that the property exists and that it has a setter.
See here for more information on reflection.