I'm new to c# and I was wondering if someone could tell me how to create a global module for changing a form like you would do in vb, and then how to call that module.
Thanks
Update:
Ok so i have multiple forms and instead of writing the same 2 lines over and over, which are..
Form x = new Form1();
x.Show();
Is it possible to add this to a class to make it easier. How do i do it? never made a class before. got the class up but unsure how to write the code.
There is nothing as Global Module in C# instead you can create a Public class with Static Members like:
Example:
//In a class file
namespace Global.Functions //Or whatever you call it
{
public class Numbers
{
private Numbers() {} // Private ctor for class with all static methods.
public static int MyFunction()
{
return 22;
}
}
}
//Use it in Other class
using Global.Functions
int Age = Numbers.MyFunction();
No, this requires help from a compiler. A VB.NET module gets translated to a class under the hood. Which is very similar to a static class in C#, another construct that doesn't have a real representation in the CLR. Only a compiler could then pretend that the members of such a class belong in the global namespace. This is otherwise a compat feature of the VB.NET compiler, modules were a big deal in the early versions of visual basic.
A static class declared without a namespace is the closest you'll get in C#. Util.Foo(), something like that.
The answer with public class using static MethodName is close. You could take it a step further and make the class static too.
Here is another Stack Overflow answer that talks about it. Classes vs. Modules in VB.Net
Related
Let's say I have an enum named ExitCodes. I also want to have a method called ErrorCodes.Quit. In C++, you can put methods under namespace, while in C# you can't. So, you can have both the enum and the method under the namespace ExitCodes in C++, but in C# you're limited. I wanted to ask two questions about those differences.
Is there a workaround for this in C#? Can I achieve the same, somehow? I know I could make the class non-static, make the constructor private and then insanitate static instances of ExitCodes with values and a static method Quit, but that's too much work.
I want to be able to make custom types like it is in C++. For example, in C++ I can do:
using exit_code_t = int;
I doubt it's possible in C#, but why not ask here.
Is there a workaround for this in C#?
Yes, put the method (and the Enum if you want) in a class instead of a namespace. Syntactically it will look the same:
public class ExitCodes
{
public enum ExitCodes
{
...
}
public static void Quit()
{
...
}
}
Now you can use ExitCodes.ExitCodes and ExitCodes.Quit();
I want to be able to make custom types like it is in C++
In C++ that just gives an alias to the int type. You can do the same thing in C#, but you have to use the actual type name, not the int keyword:
using System;
using MyInt = System.Int32;
public class Test
{
public static void Main()
{
// your code goes here
Console.WriteLine(typeof(MyInt).ToString()); // will print System.Int32
}
}
One difference in C# is that the alias only applies to the current file. So it not exactly the same as the C++ alias/typedef but it's as close as you're going to get.
In Java, we need to have at least a class to hold the main method.
When I create a C# project, the skeleton code looks similar to the Java skeleton codes.
However, should there always be at least one class for the main function in C#?
namespace Hello_World
{
class Hello //Is it compulsory to have this class ?
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
}
Edit: I am assuming at least one class is needed in a most basic C# program as the main method needs to be contain within a class. Since main() is needed to run a program, at least one class is needed. Am I right to say that?
No, not necessarily. You can have a struct also. Following is a perfectly valid c# program.
namespace NoClass
{
struct Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
}
}
Fact that Method should be inside a type in c# you need a enclosing type for your main method. It can be struct or class. It is your choice. but you can't have global funcions in c#.
If you use CS-Script, which is a way to use C# similarly to scripting languages, it's able to execute code without a class.
Granted, that's hardly traditional C#.
Since C# has not a code container/scope that can hold variables and functions - like modules in F# or VB - then yes, you have to define a type (class or struct and not a structural type; which in this scope would be an interface) to hold your code.
In fact you can not have any code out of a class or struct in C# (enum and assembly level attributes does not count!).
I use Resharper tool in visual studio
Consider a very simple class written below.
class Test()
{
//constructors do not have any return type.
Test()
{
System.Console.WriteLine("Hello World!");
}
static Test()
{
System.Console.WriteLine("Hello World in Static constructors");
}
public void A()
{
System.Console.WriteLine("A simple function in a class");
}
}
class Program
{
static void Main(string[] args)
{
var asa = new Test(); //Implicitly Typed local variables.
asa.A();
}
}
Using var (the compiler has to infer the type of the variable from the expression on
the right side of the initialization statement).
I have some clarification questions and they are below.
Extra burden to compiler?
How many constructors a class can have?
Why is static constructor called first ? (I checked out by putting a breakpoint?)
Why not Test asa = new Test(); is not preferred by Resharper?
Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)
Thanks in Advance.
Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.
A class can have any number of constructors... although it will become unwieldy pretty quickly.
The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class type is created.
Any of the static members of the class type are referenced.
You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.
Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
As many as you want as long as they are distinguishable.
Static constructors are part of the type definition. They are invoked when the type is first referenced.
What message are you receiving? R# is configurable.
Edit:
(You can't beat the Skeet).
yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.
There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)
I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)
I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:
I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
I tend to use var:
var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).
Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.
Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.
1) Every single class can have only one static constructor.
Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.
class Test
{
static Test() {...}
static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}
2) Static constructor should be declared without any access specifier.
Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.
3) Static constructor must operate only on static variables of that class
Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.
4) Why should I use a static constructor ? Give me one good example
Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".
5) When exactly a static constructor is called ?
Answer: The user has no control on when the static constructor is executed in the program.
.As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."
6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?
Answer: The base class constructor is called first and then the derived class constructor.
Code example
class DerivedClass : ParentClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
class Program
{
static void Main(string[] args)
{
var a = new DerivedClass(); //Implicitly Typed local variables.
}
}
7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?
Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)
**8)Bonus question on inheritance. Does a class inherit from two different classes ?
Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,
interface Test
{
void abc();
}
class DerivedClass : ParentClass, Test //Test should not be a class. It can be a interface.
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
public void abc()
{
//should be publicly defined!
//non public method could not implement from interface Test
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
And I use this in obvious ways like
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
My question is: Why is it necessary to wrap these static methods in a static class?
It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
In C#, any method has to be declared inside a class. That's just how the language is specified.
A static class is actually more akin to a module than a class, so I too think you should be able to either:
define a function outside a class or;
import a module the same way you import a namespace (with using)
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor are begging to be string extension methods.
This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)
It would be somewhat awkward to have methods just dangling around in a random namespace.
I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.
Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.
It's more of an organizational design than anything to due with technical limitations.
A static method is a method called in a single instance of a class that is created at run-time.
This is a question for the .NET philosophers:
It is my understanding that Microsoft consciously denied use of private classes in C#. Why did they do this and what are their arguments for doing so?
I, for example, am building a large application that includes a reporting tool. This tool uses a lot of business objects that are used only within the reporting tool and not in other parts of the project. I want to encapsulate them for use only within the reporting tool itself.
Great decision is creating separate project in VS for this tool, and I'll do like that, but I'm interesting, what if I can't do this - for exmple our architecture wasn`t good enough, and we have big single project.
Behind "private class" I mean a class that can't be used in any other namespace, except its own.
My question was not - how can I simulate this, or do in another way. I'm just wondering, why not use private keyword with class keyword without any parent classes. I`m thinking there should be some reason, and I want to know it
Allowing classes to be private to a namespace would achieve no meaningful level of protection.
Any assembly in the world could simply reference your dll, and start writing code in your namespace which accesses your supposedly private classes.
I think that's possibly the answer you'd get from Microsoft.
There's a workaround for this, but you might not like it.
Instead of using a namespace to scope your classes, use a public static partial class:
Before:
namespace MyCompany.Foo {
class Bar { }
public class Baz { }
}
After:
namespace MyCompany {
public static partial class Foo {
private class Bar { }
public class Baz { }
}
}
This construct, like a namespace, can span multiple files in the same project. But unlike a namespace, it cannot "escape" from your project (other projects cannot define other members inside Foo).
There's an added advantage that you can have utility methods that seem to have no class for code inside Foo.
The disadvantage is that, to use your non-private classes outside of your fake namespace, you have to reference them inside Foo:
using MyCompany;
// ...
var baz = new Foo.Baz();
This can be mitigated by using an alias for the class:
using Baz = MyCompany.Foo.Baz;
// ...
var baz = new Baz();
But you'd have to do it for each non-private class that you want to use.
UPDATE
It's interesting to note that C# 6 will have static using statements, which could effectively improve this proposal to use a public static partial class as a "module". You would just "use" the "module" to access its types directly.
Hopefully, it will work like this:
using MyCompany.Foo;
// ...
var baz = new Baz();
Just as if Foo was a namespace.
You can create a private class, as a member of another type:
public class Outer {
// ...
private class Inner {
// ...
}
}
and Inner is only visible to members of Outer.
At the outermost level (i.e. in a namespace) private as per its definition would not make sense (since there is nothing to be private in). Instead use internal (visible to the containing assembly's members only).
You can define a private class, but it can only be used by its containing class.
If you want a class that is only visible within a particular assembly (DLL/EXE/etc.), then you should declare it as internal (Friend in VB)
True but you can get a pretty close simulation of this with internal classes and the internalsvisibletoAttribute if the namespace is split across multiple assemblies.
Also remember that a class within another can be private to the outer class. The outer class can be considered a namespace for this purpose.
So I guess you want to do this
namespace Baz
{
private class foo
{
private int _bar;
}
}
If yes. Then what is the purpose foo will server. At namespace can you be more restrictive than internal , and make any use of the class.If I could do this where will I use this .
That is why you have this compile time validation.
Now Inside a Public Class it makes sense to have a private class. I cannot explain it better this Private inner classes in C# - why aren't they used more often?.