Is it possible to change the display syntax"Console.WriteLine" in C#? - c#

I'm new in C# programming, can someone tell me on how to change display syntax in C#?
What I would like to output is that instead of:
Console.WriteLine("Hello");//output is "Hello"
I will change Console.WriteLine to other words, but still its use is for displaying output.
PrintIt("Hello");//output is "Hello"
I wanna use it in textbox and display it in the label. How to do this?
I'm hoping that you can help me. Thank you

You can define new procedure PrintIt() for that
public void PrintIt(string message){
Console.WriteLine(message);
}
public static void Main(String []args){
PrintIt("Hello");
}

Your Can Create a method like the Guy before me showed you or even u can create a Snippet and then use it every time you start a new project without the need to write the method again.
A code snippet is a block of reusable code that you can insert where you need it in your code. Snippets can be simple or more complex—for example, blocks such as try-finally and if-else are commonly used, but you could also use snippets to insert entire classes or methods.
For instance if you are familiar with the shortcut ctor you will know that tapping twice after you wrote that it will generate a constructor for you

Related

C# control not going into the method

I am trying to call a private method from another private method like this
UploadFeeScheduleToDb(147, finalPath);
Method definition:
void UploadFeeScheduleToDb(int UploadID, string UploadFilePath)
{
DataSet CSVData = CSVToDataSet(UploadFilePath);
}
The problem is that the C# control is coming to the method call but not going inside it. I added breakpoints like this:
As you can see, the control is reaching the breakpoint but it's not reaching to the second breakpoint inside that method. It's just skipping to lblMsg.Text... statement without any exceptions in output window.
I tried cleaning solution and rebuilding. Also, I passed constants or magic values to the method. But no luck. I don't know what is happening?
As #Silvermind and #HenkHolterman said, the UploadFeeScheduleToDb method is not doing anything productive except assigning the value to its local variable, the C# compiler will ignore this method when Code Optimization feature is turned on. I think this is called Dead Code Optimization. Correct me if I am wrong.

How to invoke method from other file in C#?

In my program, I need Memory Scanner. I've used this one: http://www.codeproject.com/Articles/716227/Csharp-How-to-Scan-a-Process-Memory
I've created a new C# file named MemoryScanner.cs and copied the code there.
How to run it from here:
private void startButton_Click(object sender, EventArgs e)
{
//here I would like to invoke the MemoryScanner
}
Thanks in advance for every help. :)
Apparently (from looking at the code of the link your provided), the entry point of the program is the static method Main in class Program in namespace MemoryScanner. Call this method to start the code.
Some points should be noted:
The implementation is left as an exercise. (If you really don't know how to call a static method in C#, please start with a good, basic C# tutorial.)
Currently, the code analyzes a process called notepad, outputs the result to dump.txt and waits for Console entry before returning. If you want to use that as part of your program, you will need to change these things. (Hint: Remove the Console parts and pass the values, which are currently hard-coded, as method parameters.)
In a nutshell: If you want to use the code, you won't get around reading and (at least partly) understanding it.
You need to add a using statement at the top of your page.
using MemoryScanner;

How to force 2 C# methods always appear together in compile time?

I have two C# methods RegisterTasks() and WaitForAll(), and whenever RegisterTasks() is called, WaitForAll() must be called in the same code block too. Just wondering if there's a way to tell C# compiler to make sure WaitForAll() always appear together with RegisterTasks(), and give a compiling error otherwise?
Thanks~
Reduce the visibility of RegisterTasks() and WaitForAll(), and expose a method that calls them both.
The short answer, as everyone else has said, is no.
I assume these methods are separate because the caller may wish to execute other code in between them. You may wish to consider creating a single combined method that takes a delegate as a parameter and then invokes that delegate when desired.
No. You need to properly document the contract and trust the end user to use the methods correctly.
No but you can do some designs. Example:
public void RegisterTasks(){
// do something
WaitForAll();
}
Or
public void RegisterTasks(){
// do something
privateWaitForAll();
}
public void WaitForAll(){
// do something
privateWaitForAll();
}
private void privateWaitForAll(){
// do something
}

Is there a way to tell the compiler to put a block of code somewhere?

I have a long method, and for reading clarity would like to put some of the code in a separate method. However, that can’t be done because that code uses the variables in the method. So I would like to put that code somewhere else and tell the compiler to insert that code in “this” place when compiling. Is there any way to do that?
I’m using visual studio.
Sounds like you're describing the Extract method and you can do this very easily, simply highlight the code you want to move and:
Right click -> Refactor -> Extract method -> Enter method name
Visual studio will deal with the rest for you. Read the docs here.
As others have said, the fact that you have the problem in the first place is a symptom of a larger code organization problem. Ideally your methods should be so short, and have so few variables, that you don't need to move big parts of their code somewhere else. The right thing to do is probably to extract portions of the code into their own methods, each of which performs one task and does it well.
As a stopgap measure, you could use code regions to help organize your code:
void BigMethod()
{
#region Frobbing code
FrobTheBlob();
// blah blah blah
// blah blah blah
#endregion
...
And now in Visual Studio the editor will let you collapse that region down into just a single line that says "Frobbing code".
If you have one long method that you can't split because you need to access the same locals, what you really have is another object that you haven't formally made into a class. Refactor your code, extracting the method and shared state into a class of its own, and then start refactoring the method to smaller, more manageable pieces.
class SomeClass
{
// whatever shared state of the class
// whatever methods of the class
public void MethodThatsDoingTooMuch()
{
// long method
// hard to split the method because of locals
}
}
to
class SomeClass
{
// whatever shared state of the class
// whatever methods of the class
public void MethodThatIsntDoingTooMuch()
{
bigSomethingDoer.Do();
}
}
class BigSomethingDoer
{
// shared locals are fields instead
public void Do()
{
// refactor long method into smaller methods
// shared locals are promoted to class fields
// this smaller class only does this one thing
// --> its state does not pollute another class
}
}
well what you ask could be done with macros probably, but if the code is much and not readable you should consider to refactor it and create another method which accepts those variables you have in the main method as parameters.
some Refactoring tools out there have features like extract-method where you select some code and this is moved to another method for you. I guess both ReSharper and DevExpress CodeRush have this feature but I am not 100% sure and I don't have any of them installed to try this right now.
You can use anonymous methods/lambdas to create functions that can access the local variables of the containing method.
But such long methods usually aren't necessary. Try decoupling different parts of the method so they don't need to share common local variables.

C#: Why can't we have inner methods / local functions?

Very often it happens that I have private methods which become very big and contain repeating tasks but these tasks are so specific that it doesn't make sense to make them available to any other code part.
So it would be really great to be able to create 'inner methods' in this case.
Is there any technical (or even philosophical?) limitation that prevents C# from giving us this? Or did I miss something?
Update from 2016: This is coming and it's called a 'local function'. See marked answer.
Well, we can have "anonymous methods" defined inside a function (I don't suggest using them to organize a large method):
void test() {
Action t = () => Console.WriteLine("hello world"); // C# 3.0+
// Action t = delegate { Console.WriteLine("hello world"); }; // C# 2.0+
t();
}
If something is long and complicated than usually its good practise to refactor it to a separate class (either normal or static - depending on context) - there you can have private methods which will be specific for this functionality only.
I know a lot of people dont like regions but this is a case where they could prove useful by grouping your specific methods into a region.
Could you give a more concrete example? After reading your post I have the following impression, which is of course only a guess, due to limited informations:
Private methods are not available outside your class, so they are hidden from any other code anyway.
If you want to hide private methods from other code in the same class, your class might be to big and might violate the single responsibility rule.
Have a look at anonymous delegates an lambda expressions. It's not exactly what you asked for, but they might solve most of your problems.
Achim
If your method becomes too big, consider putting it in a separate class, or to create private helper methods. Generally I create a new method whenever I would normally have written a comment.
The better solution is to refactor this method to separate class. Create instance of this class as private field in your initial class. Make the big method public and refactor big method into several private methods, so it will be much clear what it does.
Seems like we're going to get exactly what I wanted with Local Functions in C# 7 / Visual Studio 15:
https://github.com/dotnet/roslyn/issues/2930
private int SomeMethodExposedToObjectMembers(int input)
{
int InnerMethod(bool b)
{
// TODO: Change return based on parameter b
return 0;
}
var calculation = 0;
// TODO: Some calculations based on input, store result in calculation
if (calculation > 0) return InnerMethod(true);
return InnerMethod(false);
}
Too bad I had to wait more than 7 years for this :-)
See also other answers for earlier versions of C#.

Categories