C# - How to make programs without IDE/Visual Studio? [closed] - c#

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
I am making C# console applications in Notepad++ and MonoDevelop with only a .cs file instead of a solution. I compile the code from CMD.
I want to add two classes in my simple "Hacked" program that just simply displays a lot of 0's and 1's. EVERY time I try to make an object reference, I get an error in the compiler saying that I need to make a reference for non-static fields. Making methods static works, but I don't think that every method should be static.
So my question is, how do I make object references without an IDE?
EDIT: I have found the solution by making the variable static. And I knew that when a method was static, it could be accessed from any class without a reference. I was just testing a class reference to learn a little more about C#. But I make the class reference variable static and anything that isn't static in the referenced class works fine. Thank you all for helping me out though as your suggestions and explanations did help me.

Nice to see someone starting so simple. Object references are the same no matter if you are working in VisualStudio, or in a simple text editor.
This is actually an error in your code and not the fact that you are not using an IDE.
I'm assuming you have not gone into object oriented programming too much, and that these are simple, single class programs to help you get started.
In this case, all other methods, fields, etc, are accessed in some way from your public static Main(string[] args) method. Static methods are accessible from all classes, and do not require an object instance. Methods and fields accessed without an instance must be static.
So, in this case, yes, every method does need to be static.
Check out this question, What's a "static method"?
For example, say you create a class called Math, and create a Pow(int x, int power) (power) method (This is part of the .NET framework). You would make this function static because you want ALL classes to be able to access it without creating an instance of the Math class.
int square = Math.Pow(2, 2); //Static method, no instance needed
Now say, you make a class called Book, this class has methods such as GetPagesLeft(). In this case, it is specific to each instance of a "book", and should not be static, because it applies to each instance.
Book book = new Book(); //Create instance
int pagesLeft = book.GetPagesLeft(); //Instance method
Don't be afraid of using static methods, they are there for a reason.
Note, I'm not a professional developer, so some of the terminology I used may not be exactly correct, but I hope it gets the point across.

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// instanceMethod(); // Error calling instance method without an instance.
// Won't even compile
Program prg = new Program();
prg.instanceMethod(); // No Error calling instance method from instance
staticMethod(); // No Error calling static method without an instance
}
void instanceMethod()
{
}
static void staticMethod()
{
}
}
}

Related

Is it possible to have two variables point to the same memory address in C#? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I'm playing around with C# right now, coming from the world of C++.
I'm trying to make two object variables point to the SAME memory address, in a way that if I edit variable 1, variable 2 is also being changed.
Is this possible?
Reason I'm asking is because I would ideally like to have an instance of an object inside of one object, and then also inside of a different type of object. So that if the value is changed in one object, it changes in both. Like this (or at least something like this).
public class Demo
{
public int x;
}
public class DemoContainer1
{
public DemoContainer1(ref Demo new_demo)
{
demo = new_demo;
}
public int SetX(int x)
{
demo.x = x;
}
private Demo demo;
}
public class DemoContainer2
{
public DemoContainer2(ref Demo new_demo)
{
demo = new_demo;
}
private Demo demo;
}
Demo new_demo = new Demo();
new_demo.x = 5;
DemoContainer1 container1 = new DemoContainer1(ref new_demo);
DemoContainer2 container2 = new DemoContainer2(ref new_demo);
container1.SetX(10);
// The following should now be true... container1.demo.x == 10 AND container2.demo.x == 10
Rick -
If you're coming from the world of C++, the most important thing to remember is that any time you have an instance of a class or an interface in your code, this is roughly equivalent to a pointer in C++. We call these reference types. When you assign one class reference to another class reference variable, you are essentially doing exactly what you're asking to do, which is to have both variables point to the same object in memory.
Note there are also value types - these are the fundamental types (int, char, etc.) and structs. For struct's in particular, these behave very similarly to structs in C++, (although it's not particularly easy to obtain the equivalent of a pointer to a struct).
It can be confusing because the . operator in C# doubles as the member accessor for both reference and value types. (There is no separate -> operator like in C++). You just need to be aware of whether your data items are reference types or value types to determine whether an assignment (=) will result in the value being copied or the "pointer" (reference) being copied. Consequently, you cannot create copies of class instances by simply using the assignment operator = like you can in C++. For that you have to use the Object.MemberwiseClone method.
As observed in the comments, you don't need the ref in your situation because your method argument is already a "pointer". (The ref keyword is similar to the reference type flag (&) in C++). However, if you wanted to change the value of the input parameter new_demo itself, to assign it to a different class instance, then you would indeed need the ref.
So, if it helps as you transition, you might want to just mentally imagine the C/C++ pointer flag * after every reference type variable you define and mentally picture the -> when you see the . when you're accessing class members.
Hope this helps. As someone who also transitioned from C++ to C# I definitely can see how you would find it confusing at first. But in time you'll learn to speak both languages fluently.
Edit - I'd be curious to see your code that you say is not resulting in the right outcome. As has been pointed out, what you posted should work as written.

Harm or Benefit for Instance Methods Calling Static Methods [duplicate]

This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 8 years ago.
Is there any harm or benefit for having instance methods call static methods to do their work?
If your confused by what I mean, take a look at the example code below. StripFormatting is an instance method and static method. If another developer creates an instance of PhoneUtil then all that is needed is for the StripFormatting method to be called on the instance of the object. If a developer decides not to create an instance of PhoneUtil they can call the static method except this method has a parameter for the PhoneNumber.
public string StripFormatting()
{
return PhoneUtil.StripFormatting(this.PhoneNumber);
}
public static string StripFormatting(string psPhoneNumber)
{
string tsPhoneNumber = psPhoneNumber;
Regex toNotDigit = new Regex("\\D+");
tsPhoneNumber = toNotDigit.Replace(tsPhoneNumber, "");
return tsPhoneNumber;
}
Member function or Static methods are chosen based on your software design. There are pros and cons in relation to that design you have chosen.
In general, consider using static methods when that method has no any effect on some type internal state and does not need to store some data inside, in shorts: it's execution only.
In all oher cases conside using instance methods.
Repeat this is a basic idea,as all depends on your design.
For example: looking on the code provided I see that method you wrote can easily be made static.

Is there a difference in use or not the "this" keyword to reference a method inside the same class? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When do you use the “this” keyword?
If I have the following example:
public class MyClass {
private void MyMethod1()
{
...
}
private void MyMethod2()
{
this.MyMethod1();
...
}
}
In the "MyMethod2" is there a difference in use "this.MyMethod1()" or just "MyMethod1()"? Performance, security, good practice, or whatever? I ask this, because normally I don't use "this" to call methods in the same class, but I get code developed by other people that use it... maybe I'm wrong... or not!
Sorry if looks like a silly question, but I'm "curious" after all. Thank you!
In that specific example there is no difference - it will compile to identical bytecode.
It only makes a difference if there is a local variable or parameter with the same name as the method you want to call, in which case you need to write this to refer to the member and not the local variable.
Not performance, they will compile to the same IL.
The thing with the this keyword is that it you don't have local variables with the same naming as the class members.
private void MyMethod2()
{
Action MyMethod1 = MyMethod2;
MyMethod1(); // recursive call to MyMethod2
this.MyMethod1(); // call to real MyMethod1
}
Other than that some people like it, some does not. Follow the code standard in your team.
There is no difference from an execution standpoint. As you imply, some people use this, some don't.
Use the standard you've decided is correct, unless you are overridden by company standards.

Why doesn't C# support local static variables like C does? [closed]

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 2 years ago.
Improve this question
Why doesn't C# have local static variables like C? I miss that!!
Because they screwed up, and left out a useful feature to suit themselves.
All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses.
Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb.
Loop scope static is useful and important in many cases.
Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.
The MSDN blog entry from 2004: Why doesn't C# support static method variables? deals with the exact question asked in the original post:
There are two reasons C# doesn't have this feature.
First, it is possible to get nearly the same effect by having a
class-level static, and adding method statics would require increased
complexity.
Second, method level statics are somewhat notorious for causing
problems when code is called repeatedly or from multiple threads, and
since the definitions are in the methods, it's harder to find the
definitions.
[author: Eric Gunnerson]
(Same blog entry in the Microsoft's own archive. The Archive.org preserved the comments. Microsoft's archive didn't.)
State is generally part of an object or part of a type, not part of a method. (The exception being captured variables, of course.)
If you want the equivalent of a local static variable, either create an instance variable or a static variable - and consider whether the method itself should actually be part of a different type with that state.
I'm not nearly as familiar with C as I am C#, but I believe you can accomplish everything you could with a local static, by using a class level static that is only used for one method. Obviously, this comes with some syntactic change, but I believe you can get whatever functionality you need.
Additionally, Eric Lippert answers questions like this on his blog a lot. Generally answered in this way: "I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature." Essentially his answers generally boil down to, it costs money to add any feature, and therefore, many potential features are not implemented because they have not come out on the positive side of the cost benefit analysis.
So you want to use a static local variable in your method? Congratulations! You made another step towards becoming a real programmer.
Don't listen to all the people telling you that static locals are not "clean", that they impede "readability" and could lead to subtle and hard-to-find "bugs". Nonsense! They just say that because they are wannabe programmers! Lots of them are probably even toying around with an esoteric functional programming language during their free-time. Can you believe it? What a bunch of hipsters!
Real programmers embrace a paradigm I like to call SDD - Side effect Driven Design. Here are some of it's most important laws:
Don't be predictable! Never return the same thing from a method twice - even if it's being called with the exact same arguments!
Screw purity - let's get dirty! State, by nature, craves changing, because it is an insatiable monoid in the category of polyamorous endofunctors, i.e. it likes to be touched by as many collaborators as possible. Never miss out on an opportunity to do it the favor!
Among the tools used to code in a side effect driven manner are, of course, static local variables. However, as you noticed, C# does not support them. Why? Because over the last two decades Microsoft has been infiltrated by so called Clean Coders that favor maintainability over flexibility and control. Can you even remember the last time you have seen our beloved blue screen? Now guess whose fault is that!
But fear not! Real developers don't have to suffer from those poor design decisions. As has been mentioned before it is possible to have local variables that are kind of static with the help of lambdas.
However, the provided solution wasn't quite satisfactory. Using the previous answer our almost-SDD-compliant code would look something like this:
var inc = Increment();
var zero = inc();
var one = inc();
or
var zero = Increment()();
But that's just silly. Even a wannabe developer can see that Increment() is not a normal method and will get suspicious. A real programmer, on the other hand, can make it even more SDD-like. He or she knows that we can make a property or field look like a method by giving it the type Func<T>! We just have to initialize it by executing a lambda that in turn initializes the counter and returns another lambda incrementing the captured counter!
Here it is in proper SDD code:
public Func<int> Increment = new Func<Func<int>>(() =>
{
var num = 0;
return () => num++;
}).Invoke();
(You think the above kinda looks like an IIFE? Yes, you are right and you should be ashamed of yourself.)
Now every time you call Increment() it will return something different:
var zero = Increment();
var one = Increment();
Of course you also can make it so that the counter survives the lifetime of your instance.
That'll show them wannabe programmers!
C# is a component-oriented language and doesn't have the concept of variables outside the scope of a class or local method. Variables within a method cannot be declared static either, as you may be accustomed to doing in C. However, you can always use a class static variable as a substitute.
As a general practice, there are usually ways to solve programming problems in C# without resorting to using method-level statics. State is generally something you should design into classes and types, not methods.
Logically, yes. It would be the same as a class-level static member that was only used in that one method. However, a method-level static member would be more encapsulated. If the data stored in a member is only meant to be used by a single method, it should only be accessible by that single method.
However, you CAN achieve almost exactly the same effect in C# by creating a nested class.
Because static local variables are tied to the method, and the method is shared amongst all instances.
I've had to correct myself and other programmers who expect it to be unique per class instance using the method.
However, if you make it a static class, or static instance of a class, it's syntactically clear whether there's an instance per container-class, or one instance at all.
If you don't use these, it becomes easier to refactor later as well.
I think the idea of local statics is just as easily solved by creating public static fields to the class. Very little logical change don't you think?
If you think it would be a big logical change, I'd be interested to hear how.
class MyClass
{
public static float MaxDepthInches = 3;
private void PickNose()
{
if (CurrentFingerDepth < MyClass.MaxDepthInches)
{
CurrentFingerDepth++;
}
}
}
You can use nested-class as a workaround for this. Since C# is limiting the scope of static variables to classes, you can use nested-class as a scope.
For example:
public class Foo {
public int Increment() {
return IncrementInternal.Increment();
}
private static class IncrementInternal {
private static int counter = 0;
public static int Increment() {
return counter++;
}
}
}
Here Foo supports Increment method, but its support it by the private nested class IncrementInternal which contains the static variable as a member. And of course, counter is not visible in the context (other methods) of Foo.
BTW, if you want to access to Foo context (other members and methods) inside IncrementInternal.Increment, you can pass this as a parameter to IncrementInternal.Increment when you call it from Foo.
To keep the scope as small as possible, my suggestion is to create a nested class per each such method. And because it is probably not so common, the number of nested classes will stay small enough to maintains it.
I think it is cleaner than anonymous functions or IIFE.
You can see a live demo here.
I don't see much added benefit to local statics, if you are keeping your classes single purpose and small, there is little problem with global static pollution as the naysayers like to complain about. But here is just one other alternative.
using System;
using System.Collections;
public class Program
{
delegate bool DoWork();
public static void Main()
{
DoWork work = Foo().GetEnumerator().MoveNext;
work();
work();
work();
}
public static IEnumerable Foo()
{
int static_x = 10;
/*
do some other static stuff....
*/
main:
//repetative housework
Console.WriteLine(static_x);
static_x++;
yield return true;
goto main;
}
}
If you can imagine some sort of Lippert/Farnsworth hybrid entity announcing GOOD NEWS EVERYONE!, C# 6.0 allows the using static statement. This effectively allows you to import static class methods (and, it seems, properties and members as well) into the global scope.
In short, you can do something like this:
using NUnit.Framework;
using static Fizz.Buzz;
class Program
{
[Test]
public void Main()
{
Method();
int z = Z;
object y = Y;
Y = new object();
}
}
namespace Fizz
{
class Buzz
{
public static void Method()
{
}
public static int Z;
public static object Y { get; set; }
}
}
While this is only available in C# 6.0, from what I understand the generated assemblies should be compatible with previous .NET platforms (correct me if I'm wrong).
You can simulate it using a delegate... Here is my sample code:
public Func<int> Increment()
{
int num = 0;
return new Func<int>(() =>
{
return num++;
});
}
You can call it like this:
Func<int> inc = Increment();
inc();

Question about ambiguous calls in C#

I have a question that's not really a problem, but something that made me a little curious.
I have a class with two methods in it. One is a static method and the other one is an instance method. The methods have the same name.
public class BlockHeader
{
public static BlockHeader Peek(BinaryReader reader)
{
// Create a block header and peek at it.
BlockHeader blockHeader = new BlockHeader();
blockHeader.Peek(reader);
return blockHeader;
}
public virtual void Peek(BinaryReader reader)
{
// Do magic.
}
}
When I try to build my project I get an error saying:
The call is ambiguous between the
following methods or properties:
'MyApp.BlockHeader.Peek(System.IO.BinaryReader)'
and
'MyApp.BlockHeader.Peek(System.IO.BinaryReader)'
I know that the method signatures are virtually the same, but I can't see how I possibly could call a static method directly from an instance member.
I assume that there is a very good reason for this, but does anyone know what that reason is?
The general policy of the C# design is to force you to specify wherever there is potential ambiguity. In the face of refactoring tools that allow one to rejig whether things are static or not at the drop of a hat, this stance is great - especially for cases like this. You'll see many other cases like this (override vs virtual, new for shadowing etc.).
In general, removing this type of room for confusion will make the code clearer and forces you to keep your house in order.
EDIT: A good post from Eric Lippert discusses another reason for this ambiguity leading to the error you saw
Here's a excerpt from the C# 3.0 language specification.
The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.
The 'static' modifier is not part of the signature so your example violates this rule of unique signatures.
I don't know the reason behind the rule, though.
I think there's no technical reason to disallow it, but it is done more so to protect the programmer from himself. Consider the following example:
public static void Main()
{
BlockHeader BlockHeader = new BlockHeader();
BlockHeader.Peek();
}
The example above is perfectly valid, but if the situation you describe were allowed, would it be readable? Could you see, in the blink of an eye, whether the instance method or the static method was called?

Categories