I need to save to a different setting based on the input string. Why will this line not work?
Properties.Settings.Default + colorOptionNametoSave = selectedIndexString;
Properties.Settings.Default.Save();
Where the colorOptionNametoSave is a different color setting and the selectedIndexString is the value to save. However I get the message:
Error 2: The left-hand side of an assignment must be a variable, property or indexer.
The only work around I can think of is a switch statement, but I have a lot of colors so that would be really long. Any ideas on a more efficient solution?
if/else or a switch is what you are looking for.
You cannot concatenate a variable name!
So a solution for you would be something like this ( if colorOptionNametoSave is a string ):
if(colorOptionNametoSave == "Blue")
{
Properties.Settings.Default.Blue = selectedIndexString;
}
else if(colorOptionNametoSave == "Red")
{
Properties.Settings.Default.Red = selectedIndexString;
}
Related
My goal is to actually make a guessing game, so I created two arrays with Mysql data called answers and questions. And what I want to do is take the value from the user and if it is true, for example my first answer 'fashion' matches the guess the user entered in the textbox, I want the label to write correct and continue with the next answer and try to find the next answer
My code returns true when I enter my values in the array into the textbox, but I want them to be in order. How do you think I can use the for loop. How do you think I can use the for loop to make an ordered comparison?
for (int i=0;i<cevaplar.Count;i++)
{
string tahmin = textBox1.Text;
if(cevaplar.Contains(tahmin))
{
label1.Text = "true";
continue;
}
else
{
label1.Text = "false";
break;
}
}
}
In your code you use "cevaplar.Contains(tahmin)". With contains you're checking if tahim can be found anywhere in your array, without taking any order in account.
The solution to your problem should be quite simple. Just don't use contains in this situation but use a simple indexer to compare the elements. Try the following:
Replace:
if(cevaplar.Contains(tahmin))
{
...
}
With
if(cevaplar[i] == tahim) //here you check only if the i'th element is matching.
{
...
}
Good luck!
I've tried to make a text adventure and a got an error when I get to the "if" part. I got it to work once but not like I wanted it.
I changed it a bit and then gave up and went to the original script but it wasn't working like last time and instead gave me this error:
cs0131 The left-hand side of an assingnment must be a variable,
property or indexer
Here is my code:
Console.WriteLine("What's your name");
string name = Console.ReadLine();
Console.Write("Hello " + name);
Console.WriteLine(" do you like games?");
Console.WriteLine("yes or no");
string yes = Console.ReadLine();
string no = Console.ReadLine();
if (Console.ReadKey() = yes) { Console.WriteLine("Great!, Lets play one"); }
//the error is at "if (console.readkey()"
In C# and many languages, there is a distinction between assigning a variable is equal to a value and testing for equality.
In C# = is used to assign values. int x = 1; will create a variable with the value 1.
== is used to test a value, so you would write if (x == 100) { /* something */ }
Going on your current code, you probably should have something more like this:
Console.WriteLine("yes or no");
string answer = Console.ReadLine();
if (answer == "yes") { Console.WriteLine("Great!, Lets play one"); }
Major differences are:
You are reading the answer a user types after asking yes or no, however in your code you are then trying to re-read another answer. Which doesn't quite make sense. The console will hang until the user enters another response.
As JamesFaix said, you are then trying to assign a value to Console.ReadKey() of whatever the user responded with first, after you asked them if they want to play. Instead you should be checking if the user's response was a positive reply.
I am trying break; out of frustration. Is there an event handler I need to know about in console?
You're only setting the value of capslock once, prior to entering the loop. bool is a value type, so you get a copy of the Console.CapsLock property, not a reference to it. Your variable is never going to change value after that first assignment. What you want is something like:
while(Console.CapsLock)
{
// inform user, perhaps remove the loop and just tell them once
}
Or
capslock = Console.CapsLock;
while(capslock)
{
Console.WriteLine("CapsLock on");
capslock = Console.CapsLock;
}
On a side note, writing a message as fast as possible in a loop is probably a bad idea since it's just going to fill up the screen before the user has a chance to do anythign about it.
Not to answer your original question but it appears the reason you are checking for caps lock is you want the username that is going to be typed in in all lowercase so you can do a users.Contains(username) or something similar below where you provided in the screenshot.
A better way to do it is use the contains overload that lets you set a comparer, then use a case insensitive string comparer to test.
if(users.contains(username, StringComparer.OrdinalIgnoreCase))
{
//username existed
}
else
{
//username did not exist
}
There are similar overloads for String.Equals that lets you ignore case too
//This would return true if "username = marietjie" and "testUsername = MARIETJIE"
if(username.Equals(testUsername, StringComparison.OrdinalIgnoreCase))
{
//username matched
}
else
{
//username did not match
}
The solution for this kind of problem!!
i would like to refactor this code. Maybe if possible by using a switch? Or is it the same in terms of performance?
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
}
if (rawUrl.Contains("mypage2.aspx"))
{
}
etc..
Not directly, since you want a "contains" relation, rather than an exact equality.
However, if you so desire, you could do it indirectly by attempting to parse the page name out of what I assume would be the URL, storing it in a separate String variable, and switching on that String.
For example:
// Get the URL from some external source (wherever you're already getting it from)
String rawUrl = "http://www.example.com/foo/bar.aspx";
// Means of parsing will be dependent on the format in which you expect the URL.
String page = rawUrl.Substring(rawUrl.LastIndexOf("/") + 1);
switch (page) {
case "bar.aspx":
// Do stuff
break;
case "foo.aspx":
// Do stuff
break;
}
And, of course, please take this parsing methodology with a grain of salt; this example was to show you that it is possible, but note that this method of parsing could potentially throw an exception in a number of cases, but I've omitted those checks for the sake of brevity.
Switch Cases must be a constant value. You're best bet there is to use if/else like so:
string rawUrl = context.Request.RawUrl ?? string.Empty;
if (rawUrl.Contains("mypage.aspx"))
{
//code
}
else if (rawUrl.Contains("mypage2.aspx"))
{
//more code
}
If you're concerned about performance (which is good!) then the else is the way to go. While not using an else will have the same functionality, by adding the else, you're telling the code to not process any of the other if conditions. So 10 if statements will result in 10 if conditions being processed not matter what, while 10 if/else statements might result in 10, or it might only result in 1.
EDIT:
Thought about this some, and I noticed you were using the context object. If you really wanted a switch statement, you can do the following:
string page = context.Request.Url.Segments.Last();
switch(page)
{
case "mypage.aspx":
//code
break;
case "mypage2.aspx":
//more code
break;
}
Not for a contains.
Try to isolate page name alone and you can could do it.
switch(pageName)
{
case "mypage.aspx";
break;
case "mypage2.aspx";
break;
}
I think it is better to use a Dictionary.
First, extract the file name from the raw url.
Then, use a Dictionary<string,TValue>.
If the actions to the pages are almost the same, set TValue to the type of the data associated with the pages.
If the actions are very different, set TValue to a delegate type such as Action.
I've found what seems to be the C# equivalent of a FOR-CASE structure in a project I'm working on:
foreach (string param in params.Split(';'))
{
string[] parts = param.Split('=');
string key = parts[0].Trim().ToLower();
string value = parts[1].Trim();
switch (key)
{
case "param1": this.param1 = value; break;
case "param2": this.param2 = value; break;
case "param3": this.param3 = value; break;
case "param4": this.param4 = value; break;
default: break;
}
}
(Variable names changed to protect the guilty.)
How would you implement this code?
I don't think the code in your question is anything like the code you linked to....
The code in the question looks like something I might do if I wrote a command line tool.
Am I stupid for not seeing whats wrong with the code in the question?
An alternative is to use reflection to fill parameter value variables. I've done it that ways sometimes too.
BTW: I once wrote a program in a script language that had switch as the only flow control mechanism and no gosub/return. The code in my program was structured a bit like the one you linked to. A massive switch on a sort of instruction pointer variable that got reassigned at the end of every case and an almost infinite loop around the switch. It got the job done.
I see you that you already have multiple fields in your class that you use to hold the variables. In that case, what you are doing is fine.
Otherwise, you can have 1 HashTable (maybe add in the C# indexor as a twist) to hold all of them, and your loop will end up like this:
foreach (string param in params.Split(';'))
{
string[] parts = param.Split('=');
string key = parts[0].Trim().ToLower();
string value = parts[1].Trim();
MyHashTable[key] = value;
}
The problem with this approach is that you should only have 1 type of value. For example, if your param list can contain both string and int types, it makes the code messier, especially you need to perform error checking and validation and stuff.
I personally would stick with what you already have.
You could use reflection for this:
Type t = this.GetType();
foreach (string param in params.Split(';'))
{
string[] parts = param.Split('=');
string key = parts[0].Trim().ToLower();
string value = parts[1].Trim();
t.GetProperty(key).SetValue(this, value, null);
}
For what it's worth, the WTF article was a WTF because its outer loop was completely useless, as noted in the article - it was just as easy, and more direct, just to set an index variable directly than to loop and test it.
Not sure if I understand either but it sounds like you're complicating yourself. Don't reinvent the wheel, use BCL classes as much as you can, these classes are proven to work efficiently and save you lots of time. Sounds like you could implement it with some sort of Dictionary<,> along with, like Guge suggested, Reflection.
I actually think the OP's code is fine. It's not perfect -- there might be simpler or cleaner ways to do it, but it effectively allows for readable mappings between member/property names and input-parameter names. It leaves your properties strongly typed (unlike the hashmap/dictionary solutions, unless your class has only one type for all its properties...) and gives you one fairly-obvious place to fix or add mappings.
Or Regex:
string parms = "param1=1;param2=2;param3=3";
string[] parmArr = parms.Split(';');
string parm1 = Regex.Replace(parmArr[0], "param1=", "");
string parm2 = Regex.Replace(parmArr[1], "param2=", "");
string parm3 = Regex.Replace(parmArr[2], "param3=", "");