Kind of embarassing to ask this question as it feels like it should be obvious but after god only knows how many google searches I cant seem to find what I'm looking for. Perhaps im just searching the wrong words?
anyway I've started working on a basic to get to grips with the WP8 device to start porting some of my old c# games to play on my shiny new lumia.
anyways. I've created a simple app with a few pages that dont really do a whole lot. few buttons/images etc. the buttons do things and all thats fine and dandy. now i'm wanting to use a particular function on multiple pages but cant for the life of me find where I can put a function in 1 single place that I can use from everywhere.
ie
public void(string blah) {
MessageBox.Show("This is button " + blah);
}
I'd rather not have to have a copy of the same functions on all my created pages. I've got my class file and that works all nice and dandy. Ideally i'd like a functions file. Even if I have to declare it with a line I'd be happy. beats having hundreds of line of the same code throughout my app.
The keyword is static
public static void print(string blah) {
MessageBox.Show("This is button " + blah);
}
lets say this function is in class x
then you would call it as followed: x.print("blah");
You can take a look at WP8 how to create base-page & use it to create base pages with methods, or like what #Svexo said, you can create static functions but also bear in mind Static classes in C#, what's the pros/cons? that recklessly creating static functions all over the place is going create problems in the long run
Related
I read about events and delegates. I think I understand how they work but I do not understand why should I use them.
For example, I have online shop where customer has balance and is buying products using this money.
This is enough to do the job.
When user buys something, sells something or deposits money - UserWallet class is called.
class Shop
{
public static void BuyOrderFilled(){
if(userHasBalance()){
UserWallet userWallet = new UserWallet();
userWallet.DeductMoney();
}
UpdateInventory();
}
public static void SellOrderFilled(){
//Sell order has different logic
if(userHasProduct()){
UserWallet userWallet = new UserWallet();
userWallet.RemoveProductFromUser();
}
UpdateInventory();
}
}
class Deposit{
public static void UserGotDeposit(decimal amount){
UserWallet userWallet = new UserWallet();
userWallet.FillUserBalance(amount);
}
}
class UserWallet{
public void DeductMoney(){
//Some logic
}
public void RemoveProductFromUser(){
//Some logic
}
public void FillUserBalance(){
//Some logic
}
}
public class Main(){
Shop.BuyOrderFilled();
Shop.SellOrderFilled();
Deposit.UserGotDeposit(100);
}
Why should I use Events or delegates when I can just call UserWallet methods whenever I need them?
You don't have to use them..
..it's just that sometimes it's super handy to be able to pass methods around like they were data.
Quite often the utility in this is if you're providing a library for other people to use and you want to make it useful for them but you don't know a thing about their code or how they'll use it. An obvious one is List<T> in the framework; you might be writing something like it and want to provide a way for people to search if, but you don't know what kind of objects they will put in the list or how they want to search for them.
If, however you just provide them with a method like Find(delegate) then it's a "method that takes a method as a parameter" - you declare to the user "provide Find with a method that takes a T and returns a boolean of true if it should be included in the search results", then it means they can write a method like this:
bool IsSmith(Person p) {
return p.LastName == "Smith";
}
And they can pass it to your list Find method, your method runs their method, gives it the List object, gets a bool and decides what to do based on the result
var smiths = myListOfPeople.Find(IsSmith);
Nowadays we don't usually write the method out so long hand, we use the funky inline declaration where we just provide the parameter name and the logic, and the compiler inserts all the other stuff it can work out
var smiths = myListOfPeople.Find(p => p.LastName == "Smith");
In essence you can control every part of the process when you wrote your List class, you can implement the find, you can return the results - but in making your List truly flexible and letting people store what they want in it, you create a gap in the middle where you can't know how to search for a Whatever that the user put into it. Being able to let them pass a method in (of a known arguments type and return type) that you can call closes that gap
Another example; events this time but they're no different. An event is just a list of methods that the user of your class can fill with "bits of code that shall be run when something happens"
Take a button click: you want to download a file, your coworker wants to save an image, I want to calculate factors of a number entered in a text box.. We're all using that same Button class but we all want to do different things when we click our different buttons, so the easiest way for Microsoft to make the perfect button is to just leave that "do this when clicked" part for us to fill in, and that's done by having a way to associate a delegate (method passed round like a variable) with the button, and coding the button so that it runs the delegate when it's clicked, whatever the delegate may do
So all that is great for Microsoft, who create Buttons and Lists and other generic things for us to enjoy, but does it have a place for us in our own code? Sure, though more rare, I find it helpful to make some helper class for example- something that launches ffmpeg and reads from its output stream.. and mostly it's just nonsense but occasionally interesting messages are sent, so I might make an event that I raise when such a message is sent.. I use my helper in one project and I'm looking for dropped frames, in another I want to know if silence is detected.. In those cases I suppose the "person who provides the library to the person who consumes the library" was me at both ends. I have other projects where I want to perform similar tasks on different data, the writer routine is the same but the parsing is different; being able to pass a method to say how to pull a name out of this object but a number out of that one makes life a lot nicer than having some massive "if object is a person pull the name, else if object is a building pull the number and street" conditional block in a place it doesn't belong
I am creating a program which shows a form with a text field and activate button, there are certain code which are entered by the user in the text field and on clicking activate button it does the work based on the code inputted by user.
I have successfully created a form and in the activate button click event it calls the method of another class (named Output) like below
Output o = new Output();//Created object for output class
o.effect(s.Text);//here effect() is function of Output and s is textfield
And in Output class's effect() function
void effect(String str)
{
switch(str)
{
case "code1": Console.Write("you enter code1"); //all the things to be done if code1 input
break;
...
...
default: ...;
break;
}
}
The above classes were successfully compiled and run properly. But now I want to make a dll support for this program so that whenever I have to add more code I can just easily create a new dll (Say, Outputversion2.dll) in which there are code like above Output class which can be entered in main program form.
Something like a code extension...
I don't want to mistakenly damage the main program by editing every time to add more codes that's why I thought of it.
Hope you understand what I want to do.
I am just beginner with c# , just learned a month ago.
Sorry for any Grammar error, my English is also not so good.
Thank U.
I'm not sure what you are trying to do here. If you're hoping to be able to dynamically add new DLLs, each with a set of handlers (i.e. cases), then you should probably use the Managed Extensibility Framework. Otherwise, if what you are trying to do is to simply have all handlers in one separate DLL that can be replaced at any time, you should place the Output class in a Class Library, which will compile into a DLL; you can then swap out versions of this DLL without worrying about changing the main program, so long as you don't change the interface (the classes and their functions' return types and parameters; you can change the code inside the function as much as you want).
Also, if your worried about destabilizing the main program, I would recommend keeping backups of the source code, and not releasing new versions until you have fully tested them multiple times.
I hope this helps.
I'm writing the simple card game "War" for homework and now that the game works, I'm trying to make it more modular and organized. Below is a section of Main() containing the bulk of the program. I should mention, the course is being taught in C#, but it is not a C# course. Rather, we're learning basic logic and OOP concepts so I may not be taking advantage of some C# features.
bool sameCard = true;
while (sameCard)
{
sameCard = false;
card1.setVal(random.Next(1,14)); // set card value
val1 = determineFace(card1.getVal()); // assign 'face' cards accordingly
suit = suitArr[random.Next(0,4)]; // choose suit string from array
card1.setSuit(suit); // set card suit
card2.setVal(random.Next(1,14)); // rinse, repeat for card2...
val2 = determineFace(card2.getVal());
suit = suitArr[random.Next(0,4)];
card2.setSuit(suit);
// check if same card is drawn twice:
catchDuplicate(ref card1, ref card2, ref sameCard);
}
Console.WriteLine ("Player: {0} of {1}", val1, card1.getSuit());
Console.WriteLine ("Computer: {0} of {1}", val2, card2.getSuit());
// compare card values, display winner:
determineWinner(card1, card2);
So here are my questions:
Can I use loops in Main() and still consider it modular?
Is the card-drawing process written well/contained properly?
Is it considered bad practice to print messages in a method (i.e.: determineWinner())?
I've only been programming for two semesters and I'd like to form good habits at this stage. Any input/advice would be much appreciated.
Edit:
catchDuplicate() is now a boolean method and the call looks like this:
sameCard = catchDuplicate(card1, card2);
thanks to #Douglas.
Can I use loops in Main() and still consider it modular?
Yes, you can. However, more often than not, Main in OOP-programs contains only a handful of method-calls that initiate the core functionality, which is then stored in other classes.
Is the card-drawing process written well/contained properly?
Partially. If I understand your code correctly (you only show Main), you undertake some actions that, when done in the wrong order or with the wrong values, may not end up well. Think of it this way: if you sell your class library (not the whole product, but only your classes), what would be the clearest way to use your library for an uninitiated user?
I.e., consider a class Deck that contains a deck of cards. On creation it creates all cards and shuffles it. Give it a method Shuffle to shuffle the deck when the user of your class needs to shuffle and add methods like DrawCard for handling dealing cards.
Further: you have methods that are not contained within a class of their own yet have functionality that would be better of in a class. I.e., determineFace is better suited to be a method on class Card (assuming card2 is of type Card).
Is it considered bad practice to print messages in a method (i.e.: determineWinner())?
Yes and no. If you only want messages to be visible during testing, use Debug.WriteLine. In a production build, these will be no-ops. However, when you write messages in a production version, make sure that this is clear from the name of the method. I.e., WriteWinnerToConsole or something.
It's more common to not do this because: what format would you print the information? What text should come with it? How do you handle localization? However, when you write a program, obviously it must contain methods that write stuff to the screen (or form, or web page). These are usually contained in specific classes for that purpose. Here, that could be the class CardGameX for instance.
General thoughts
Think about the principle "one method/function should have only one task and one task only and it should not have side effects (like calculating square and printing, then printing is the side effect).".
The principle for classes is, very high-level: a class contains methods that logically belong together and operate on the same set of properties/fields. An example of the opposite: Shuffle should not be a method in class Card. However, it would belong logically in the class Deck.
If the main problem of your homework is create a modular application, you must encapsulate all logic in specialized classes.
Each class must do only one job.
Function that play with the card must be in a card class.
Function that draw cards, should be another class.
I think it is the goal of your homework, good luck!
Take all advices on "best practices" with a grain of salt. Always think for yourself.
That said:
Can I use loops in Main() and still consider it modular?
The two concepts are independent. If your Main() only does high-level logic (i.e. calls other methods) then it does not matter if it does so in a loop, after all the algorithm requires a loop. (you wouldn't add a loop unnecessarily, no?)
As a rule of thumb, if possible/practical, make your program self-documenting. Make it "readable" so, if a new person (or even you, a few months from now) looks at it they can understand it at any level.
Is the card-drawing process written well/contained properly?
No. First of all, a card should never be selected twice. For a more "modular" approach I would have something like this:
while ( Deck.NumCards >= 2 )
{
Card card1 = Deck.GetACard();
Card card2 = Deck.GetACard();
PrintSomeStuffAboutACard( GetWinner( card1, card2 ) );
}
Is it considered bad practice to print messages in a method (ie: determineWinner())?
Is the purpose of determineWinner to print a message? If the answer is "No" then it is not a matter of "bad practice", you function is plain wrong.
That said, there is such a thing as a "debug" build and a "release" build. To aid you in debugging the application and figuring out what works and what doesn't it is a good idea to add logging messages.
Make sure they are relevant and that they are not executed in the "release" build.
Q: Can I use loops in Main() and still consider it modular?
A: Yes, you can use loops, that doesn't really have an impact on modularity.
Q: Is the card-drawing process written well/contained properly?
A: If you want to be more modular, turn DrawCard into a function/method. Maybe just write DrawCards instead of DrawCard, but then there's an optimization-versus-modularity question there.
Q: Is it considered bad practice to print messages in a method (ie: determineWinner())?
A: I wouldn't say printing messages in a method is bad practice, it just depends on context. Ideally, the game itself doesn't handle anything but game logic. The program can have some kind of game object and it can read state from the game object. This way, you could technically change the game from being text-based to being graphical. I mean, that's ideal for modularity, but it may not be practical given a deadline. You always have to decide when you have to sacrifice a best practice because there isn't enough time. Sadly, this is all too often a common occurrence.
Separate game logic from the presentation of it. With a simple game like this, it's an unnecessary dependency.
I'll exemplify, since I'm not sure if I'm asking the question correctly (English is not my primary language, plus I'm still learning C#).
I've started going through Project Euler, and decided to create an application to keep track of my results, and to put my little C# knowledge to test.
In a particular class I hold static functions that are used to solve each of the problems.
static class Answers()
{
public static string A1(){...}
public static string A2(){...}
public static string A3(){...}
//it goes on
}
Problem objects will be created like this (Problem class definition and object creation in runtime).
class Problem
{
public string Description;
public Solution SolutionFinder;
public Problem(string Desc, Solution Solver)
{
this.Description = Desc;
this.SolutionFinder = Solver;
}
public delegate string Solution();
public string SolveProblem()
{
return SolutionFinder.Invoke();
}
}
This is on my Form creation code:
{
...
List<Problem> Euler = new List<Problem>();
Euler.Add(new Problem("Find the sum of all the multiples of 3 or 5 below 1000.", Answers.A1));
Euler.Add(new Problem("By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.", Answers.A2));
Euler.Add(new Problem("What is the largest prime factor of the number 600851475143 ?", Answers.A3));
...
}
I got the classes and even the delegate thing to work correctly, and I'm thrilled with that. Then I finally decided to show the whole thing on a form. What I'm trying to show is: the description of the problem (this is done) and the code for each method (whatever is inside A1, A2, etc.) whenever I solve a problem using my form.
Is that clear? It's just that I want my form to show the result and how I got the solution for each problem, but without having to retype the contents of each method just for display - the methods are already there.
And please don't mind the messy code and overuse of public members: I understand it's a bad practice, but for now I'm just trying to get through this personal project, and I believe it's OK to do this here since it's just a small learning experience.
Thanks.
[EDIT]
The format I'm looking for is:
void UpdateForm(int Current)
{
Problem CurrentProblem = Euler[Current-1];
string Desc = CurrentProblem.Description;
string Code = CurrentProblem.SolutionFinder.Method.ReturnType.Name;
//I got this far, but I need to display more than just the name of the method!
...
}
To Clarify
Given the method:
public static string A1() {
var answer = 1 + 1;
return answer.ToString();
}
Is it possible to obtain the following lines in a string..?
var answer = 1 + 1;
return answer.ToString();
While it's not the fanciest approach, if you set the "Copy to Output Directory" value to "Copy Always" (or "Copy if newer") via the Properties of the source file (right-click/ Properties), you can parse the code file on your own while optimizing for your coding style.
To add, are you aware that you are basically rebuilding NUnit, aside from the source code dump?
Since at runtime the code is in IL (intermediate language), you actually don't have the readable code at your disposal.
Anyway you could use reflection to create an on-fly decompiler, or use third party library like this one or this one to decompile the methods... but I don't know if they expose some API, I just know them as GUI tools.
You might think about storing your solutiuons (source code) in text files.. (eg. Problem1.projecteuler, ProblemN.projecteuler) and loading these text files both for display and for compilation/execution plugin-style. Check out System.Reflection namespace and do some web searches for "C# plugin tutorial" or some such to get started.
valeriano your static methods could be Linq Expressions, then you could iterate through each node of the expression. Using Reflection works too but you need more code
There's no easy way to run code (ie: contents of a method) from a string since C# is already compiled before its executable is launched.
However, there are tricks you can do with Reflection and Diagnostics, but that requires you to run your code in Debug mode. If it's just a small app, this shouldn't be a problem. But larger applications with suffer performance issues when ran in debug mode.
For more info: Execute a string in C# 4.0
Sorry i am new to C#. I have a program, where there is a class CatchFS. The main function in the class , has the code
CatchFS fs = new CatchFS(args);
fs.Start();
Can someone tell me what it means. I hv heard of thread.start() but object.start() is new to me . Am i even thinking right ?
Thanks a lot, Yes it is derived from a class called FileSysetm.cs. The start does this : public void Start ()
{
Console.WriteLine("start");
Create ();
if (MultiThreaded) {
mfh_fuse_loop_mt (fusep);
}
else {
mfh_fuse_loop (fusep);
}
}
Now im trying to do a fusemount. The program starts and it hangs. there is some call that was not returned and i couldnt figure out which one. I tried using debug option of monodevelop, but no use, it runs only in my main function and I get thread started and thats it !!
I think the file FileSystem.cs is from library Mono.fuse.dll. Thanks for all your time. I hv been looking at this question for 2 whole days, and I dont seem to figureout much as to why the code wont proceed.Im expecting my azure cloud storage to be mounted in this fusemount point. My aim is after running this code I should be able to do an ls on the mountpoint to get list of contents of the cloud storage. I am also suspecting the mountpoint. Thanks a lot for providing me all your inputs.
There is no object.Start method. Start must be a method of the CatchFS class or some base class from which CatchFS derives.
If possible, consult the documentation for the library CatchFS comes from. That should hopefully explain what CatchFS.Start does.
If the documentation is sparse or nonexistent but you do have the source code, you can also simply take a look at the CatchFS.Start method yourself and try to figure out what its intended behavior is.
If there's no documentation and you have no source code, you're dealing with a black box. If you can contact the developer who wrote CatchFS, ask him/her what Start does.
One final option would be to download .NET Reflector and use that to disassemble the compiled assembly from which CatchFS is loaded. Treat this as a last resort, as code revealed by Reflector is typically less readable than the original source.
Start is a method on the CatchFS class (or one of its parent classes) - you'll have to read the documentation or source for that class to find out what it actually means.
According to the MSDN Docs for Object, there is no Start method. This must either be a method of CatchFS or one of it's base classes.