Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I want to check myString every 2 seconds to itself to see if its changed. myString if influenced by other code
I'm wondering if we have to store myString every 2 seconds somewhere else (lets say X) and then compare X to myString
You might just be asking the wrong question only due to your lack of knowledge about features in the language.
Checking every 2 seconds, you could look into running a separate task that delays 2000 milliseconds and checks and does something.
You could have a backgroundworker thread doing similar.
You could create public getter/setter so that when it DOES change, you can act on it. This way you dont waste resources checking every two seconds. This last option MIGHT work for you.
public class YourExistingClassSomewhere
{
private string _myString = "just setting to a default start value";
public string MyString
{
get {return _myString;}
set {
// even if attempting to assign a new value,
// if the incoming new value is the same, just get out.
if( _myString == value )
return;
// it was a different value, save it
_myString = value;
// Then you could call some other method to display message.
DoWhenStringChanges();
}
}
public void DoWhenStringChanges()
{
Messagebox.Show( "it changed: " + MyString );
}
public YourExistingClassSomewhere()
{
MyString = _myString; // try to set it to its own value, no change made
MyString = "something new"; // this will trigger the message notification
}
}
You could ALSO do via exposing an "event" which exposes an event handler that other objects can get registered with, so when something happens, ANYTHING that is registered to the event gets notified. So, it does not have just one output reach. I could post that option as well if you think that might help.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
This is the start of a very simple banking application.
I have abstract base class which this class inherits from.
public class CheckingAccount : AccountBase
{
public override bool Withdraw(float withdrawAmount)
{
if ((Balance -= withdrawAmount) < 0)
{
return false;
}
else
{
Balance -= withdrawAmount;
return true;
}
}
}
The withdraw function has an if statement which checks if the balance minus the withdraw amount would be less than 0. If it is less than 0 it returns false and does not do the operation. If it is more than 0 then it moves to the else block and does the operation and returns true.
When I test this in the main function, like this:
CheckingAccount cAccount = new CheckingAccount();
cAccount.Deposit(300);
cAccount.Withdraw(500);
Console.WriteLine(cAccount.Balance.ToString());
The final output is still -200. When I place breakpoints in the code, I see that it is going through the correct path with it not directly changing the Balance property as it just returns false however, the comparison in the if statement is still changing the actual property. i know that classes are reference types however I do not know how to pass this by value instead as I just want to check if it would be less than 0 and not actually change to stored value in the property.
I tried to do a simple comparison however this comparison ended up actually changing the property. I've tried changing around things here but nothing's really working. I'm new to programming still so this might be a silly question but I can't find any answers.
Just change -= to -. -= is a distinct binary operator that mutates the value of the first operand by subtracting the amount of the second operand. If you just want to compare the difference between the two, just use -.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm writing some code which gets properties from an object and uses them to populate a pdf.
The code I use to get items from my dictionary is below:
public static int? GetYPrintCoord(string word)
{
// Try to get the result in the static Dictionary
PrintCoord result;
if (Dict.TryGetValue(word, out result))
{
return result.Y;
}
else
{
return null;
}
}
where the dictionary looks like:
Dictionary<string, PrintCoord> Dict = new Dictionary<string, PrintCoord>();
The thing is I'm sick of checking for nulls when GetYPrintCoord(string word) is called. The fact is that if an item in the dictionary doesn't exist the whole pdf isn't worth generating because it will contain erroneous data. I was thinking instead of changing the method to:
public static int GetYPrintCoord(string word)
{
// Try to get the result in the static Dictionary
PrintCoord result;
if (Dict.TryGetValue(word, out result))
{
return result.Y;
}
else
{
throw new KeyNotFoundException();
}
}
Is this bad practise/unadvisable? Throwing an exception and crashing would actually be a lot better in user terms because then at least the user wouldn't view an invalid pdf and possibly not knowing it's invalid.
You're reinventing the wheel, this is the built-in behavior unless you need to do some logging before throwing the exception:
PrintCoord result = Dict[word]; // is equivalent to your code.
If the key is not found, an exception is thrown.
So basically you would use TryGetValue if you expect the key not to be found in the dictionary and you're ok with that. Second case would be if you don't want to use a try...catch and just use a simple if statement to handle the key not found case.
Exceptions represent, as the name suggest, exceptional cases.
If the fact that the key was not found in the dictionary denotes that something went wrong someplace else, that is, it is not something which should happen, then an exception might make sense.
That being said, if it is expected that sometimes the required key is not found, an exception might not make sense. What you can do, you could rename your GetYPrintCoord method as TryGetYPrintCoord. Then you make the method yield a boolean, True if the key was found, False if otherwise and use the out keyword to pass back the value in the dictionary.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I was wondering about coding practices, and came up witha question. Is it a good idea to predefine multiple parameters within one method - so when you call that method you don't have to pass values if the value is predefined and correct.
i.e.
private void ErrorMessage
(bool isEmpty = false, bool fromAccEmpty = false, bool toAccEmpty = false){}
So when you call it you can either call it via
ErrorMessage();
or
ErrorMessage(true, false, true);
I think this will be an alternate for you:
public class ErrorMessage
{
public bool isEmpty = false;
public bool fromAccEmpty = false;
public bool toAccEmpty = false;
}
private void ShowErrorMessage(ErrorMessage errorObject)
{
//Do your stuff here
}
Why i suggest this:
Consider the op's code:
# If we call the method as he stated in the question (Positional arguments) we cannot call the method by specifying value for second parameter without giving value to the first one.
# This can be avoided by using Named arguments as like the following:
ErrorMessage(fromAccEmpty :true);
Hence we can assign value to the second parameter only, others will be default. We can simply use the suggested method without these issues and confusions; consider the following snippets:
ErrorMessage errorBoject = new ErrorMessage();
ShowErrorMessage(errorBoject);// All default values ware assigned
errorBoject.toAccEmpty = true;
ShowErrorMessage(errorBoject); // call with value for last parameter only rest are default
errorBoject.isEmpty = true;
ShowErrorMessage(errorBoject); // only the second value is default rest of them have values
one thing to think about is this. When you see
ErrorMessage(true, false, true, false);
in the code 2 yrs from now. What does it mean? Also did you get the flags in the correct order. Although its more long-winded maybe
FribbleErrorMessage(); // some flag = true
FrobbleErrorMessage(); // some flag = false
....
is clearer. (Yes I know you would need 16 methods for all combinations or 4 flags - but maybe there are common ones to be called out, and reduce the number of flags)
Another idea is replace the bools by enums
ErrorMessage(IsError.True, EmptyAcc.False,..);
Now you can see what they mean and the compiler will ensure you pass the correct things
Or un-lucky's suggestion of passing a parameter block of some sort
ErrorMessage(new ErrorControl{IsEmpty=true});
Note that many people (including me) fronw on default arg values as opposed to overloads. Why? Because if you want to change the default behavior you have to recompile the callers, maybe not a problem for you but in general is makes encapsulation a little weaker (Same reason why you should have public get;set; accessors instead of naked public fields)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
static int Main(string[] args)
{
Guid obj = Guid.NewGuid();
Console.WriteLine("New Guid is " + obj.ToString());
Console.ReadLine();
return -1;
}
Can anybody tell me why return -1 has been used here, and what it means?
The Main method can return void:
static void Main()
{
//...
}
It can also return an int:
static int Main()
{
//...
return 0;
}
If the return value from Main is not used, returning void allows for slightly simpler code.However, returning an integer enables the program to communicate status information to other programs or scripts that invoke the executable file.
Read more here.
I'm certainly in no position to tell you why -1 was picked, but in general, that return value would be sent out to the calling application. It's called an exit code. They're generally not used these days in applications, since there's really just no use, but back in the day--and, indeed, still in this context--they were used to convey success or failure (or something else) of a console application.
For example, I might write a program that makes a network call, then returns 0 if the call is successful and, random example, 12 if there was no NIC installed. That way, if some other program was utilizing my EXE, it could understand whether the call was successful or not without having to unreliably parse some output stream.
Most modern applications have static void Main functions, because this workflow isn't useful in most situations to the end user. We use GUIs now to show off "there was an error during execution." That's not to say they aren't useful in some circumstances, obviously, for the very same reason as they were before, but the result generally isn't captured if you, say, start a program by double-clicking an icon, and thus it gets thrown away in most cases.
The return value of main is the exit code of the program. The caller can check it and react on it. On Windows the common pattern is to use 0 if the program succeeded and different positive integers for error conditions.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Sometimes I have to write big code in a class, so what I do is something like this,
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
//DoSomething and get something from database
Method-2(pass parameters that i got from database);
}
Public void Method-2(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-3(parameter);
}
Public void Method-3(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-4(parameter);
}
// and it keeps going
}
Another way
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
Method-2();
Method-3();
Method-4();
// so on....
}
}
Is this the right way of doing it and if not then what would be best way of doing it ?
Edit
#Sayse I am trying to get information from different sources and trying to build a big XML file which made me get use 4, 5 foreach loops to get data from sql etc.. so using nested methods
Both ways are good in different cases. If you have single functionalities, you should keep them separate. Second approach - calling method from method should be used when one method is part of 'outer' functionality.
Examples:
repairVehicles() {
repairCar();
repairBike();
repairTrain();
}
... but:
repairCar() {
...
repairEngine();
...
}
repairEngine() {
...
takeEngineOut();
....
}
takeEngineOut() {
...
unscrewBolts();
...
}
There cannot be a straight forward answer to your question.
First of all you should note that one method should perform one functionality. If it is true, then you can call it either way depending on your requirement.
Example:
If you have a base method takes a mathematical expression as input. And that expression contains Add, Subtract, Multiply and divide then you will call it the first way.
public int GetExpressionResult(string someExpression)
{
Divide();
Multiply();
Addition();
Subtraction();
return result;
}
in the above example the result is dependant on all four methods, so it is fine to call it like this.
now in your example 2 if the methods are totally independant of each other than you should the way you have done.
Conclusion:
There is no hard and fast rule for this, You should call the way your application demands.
As far as I understood your question, what you are describing is basically a pipeline. There is a very interesting blog (in two parts here and here) about how to elegantly tackle situations as yours.
At the end, it depends on what you're trying to do and applies, IMHO, not only to C#.
Your first option should be applied when method<i+1> is a helper for method<i>, or is included in it. I can't find an example for such a scenario.
Your second example, which is far more readable to me, should be applied when you have a long sequence of actions that need to take place. Let say:
void mainMethod()
{
ConnectToDB(); //if can't connect, log it and exit
GetUserInfo(...); //if null, log it and exit
ShowUserInfo(...);
}
In the example above, it's hard (for me) to imagine a division to methods like in your first scenario.