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.
Related
It's extremely lazy, but I'm wondering if it's possible to have two names point to the same static class in essence.
I have a long and descriptive static class name BusinessLogicServiceUtility (as example) and it's looking rather long-winded in code.
I'd love to use BLSU as an alternative, so I tried extending the long class with my short class name:
public static class BLSU : BusinessLogicServiceUtility
{
}
Which probably looks noob but as it turns out, it doesn't work.
It looks as though I could wrap each method in the long class with a method inside the short class, but there's a lot of methods, which makes maintaining it a pain and circumvents the whole laziness goal.
Is there a way of assigning two names to one static class, or some other method simply "extending" a static class?
You can create an alias for a type:
using BLSU = Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
BLSU.SomeStaticMethod();
With C# 6 you can even go further - access static members of a type without having to qualify type name at all:
using static Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
SomeStaticMethod();
Further reading: using Directive (C# Reference)
In addition, you can use using static that will allow you to use the methods without prefixing them with the class at all:
at the top of the file :
using static BusinessLogicServiceUtility;
and say you have a method public static DoLogicThings() in your static class, you can access it directly now:
public void SomeMethod()
{
DoLogicThings();
}
this was added in C#6.
I'm trying add the ability to lookup elements in a List<KeyValuePair<string,int>> by overriding the indexer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class MyList : List<KeyValuePair<string, int>>
{
public int this[string key]
{
get
{
return base.Single(item => item.Key == key).Value;
}
}
}
}
For some reason, the compiler is throwing this error:
'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'Single'.
While it is true that List<T> doesn't have that method, it should be visible because it is an extension method from the System.Linq namespace (which is included). Obviously using this.Single resolves the issue, but why is access via base an error?
Section 7.6.8 of the C# spec says
When base.I occurs in a class or struct, I must denote a member of the base class of that class or struct.
Which might seem to preclude access to extension method via base. However it also says
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
If base.I is just like ((B)this).I then it seems like extension methods should be allowed here.
Can anyone explain the apparent contradiction in these two statements?
Consider this situation:
public class Base
{
public void BaseMethod()
{
}
}
public class Sub : Base
{
public void SubMethod()
{
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base) { }
}
Here are some interesting assertions about this code:
I cannot call the extension method using ExtensionMethod() from neither Base nor Sub.
I cannot call base.ExtensionMethod() from Sub.
I can call the extension method using Extensions.ExtensionMethod(this) from both Sub and Base.
I can call the extension method using this.ExtensionMethod() from both Sub and Base.
Why is this?
I don't have a conclusive answer, partly because there might not be one: as you can read in this thread, you have to add this. if you want to call it in the extension method style.
When you're trying to use an extension method from the type it is in (or - consequently - from a type that is derived from the type used in the extension method), the compiler doesn't realize this and will try to call it as a static method without any arguments.
As the answer states: they [the language designers] felt it was not an important use case scenario to support implicit extension methods (to give the beast a name) from within the type because it would encourage extension methods that really should be instance methods and it was considered plain unnecessary.
Now, it is hard to find out what is happening exactly under the covers but from some playing around we can deduce that base.X() does not help us. I can only assume that base.X performs its virtual call as X() and not this.X() from the context of the baseclass.
What do I do when I want to call the extension method of a baseclass from a subclass?
Frankly, I haven't found any truly elegant solution. Consider this scenario:
public class Base
{
protected void BaseMethod()
{
this.ExtensionMethod();
}
}
public class Sub : Base
{
public void SubMethod()
{
// What comes here?
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base)
{
Console.WriteLine ("base");
}
public static void ExtensionMethod(this Sub sub)
{
Console.WriteLine ("sub");
}
}
There are 3 ways (leaving aside reflection) to call the ExtensionMethod(Base) overload:
Calling BaseMethod() which forms a proxy between the subclass and the extensionmethod.
You can use BaseMethod(), base.BaseMethod() and this.BaseMethod() for this since now you're just dealing with a normal instance method which in its turn will invoke the extension method. This is a fairly okay solution since you're not polluting the public API but you also have to provide a separate method to do something that should have been accessible in the context in the first place.
Using the extension method as a static method
You can also use the primitive way of writing an extension method by skipping the syntactic sugar and going straight to what it will be compiled as. Now you can pass in a parameter so the compiler doesn't get all confused. Obviously we'll pass a casted version of the current instance so we're targetting the correct overload:
Extensions.ExtensionMethod((Base) this);
Use the - what should be identical translation - of base.ExtensionMethod()
This is inspired by #Mike z's remark about the language spec which says the following:
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
The spec literally says that base.I will be invoked as ((B) this).I. However in our situation, base.ExtensionMethod(); will throw a compilation error while ((Base) this).ExtensionMethod(); will work perfectly.
It looks like something is wrong either in the documentation or in the compiler but that conclusion should be drawn by someone with deeper knowledge in the matter (paging Dr. Lippert).
Isn't this confusing?
Yes, I would say it is. It kind of feels like a black hole within the C# spec: practically everything works flawlessly but then suddenly you have to jump through some hoops because the compiler doesn't know to inject the current instance in the method call in this scenario.
In fact, intellisense is confused about this situation as well:
We have already determined that that call can never work, yet intellisense believes it might. Also notice how it adds "using PortableClassLibrary" behind the name, indicating that a using directive will be added. This is impossible because the current namespace is in fact PortableClassLibrary. But of course when you actually add that method call:
and everything doesn't work as expected.
Perhaps a conclusion?
The main conclusion is simple: it would have been nice if this niche usage of extension methods would be supported. The main argument for not implementing it was because it would encourage people to write extension methods instead of instance methods.
The obvious problem here is of course that you might not always have access to the base class which makes extension methods a must but by the current implementation it is not possible.
Or, as we've seen, not possibly with the cute syntax.
Try to cast the instance to its base class:
((BaseClass)this).ExtensionMethod()
Applied to your code:
public class Base
{
public void BaseMethod()
{
}
}
public static class BaseExtensions
{
public static void ExtensionMethod(this Base baseObj) { }
}
public class Sub : Base
{
public void SubMethod()
{
( (Base) this).ExtensionMethod();
}
}
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!).
This is a bit of a newbie question about C#. I'm using Windows Forms with Visual Studio 2008.
So, I am able to create a class with static variables and functions. For example:
namespace foo
{
public class bar
{
const static int money = 5;
public static int FuncX()
{
return 6;
}
}
}
Then, over in my form, I have a label, and I can go:
private void label1_Click(object sender, EventArgs e)
{
label1.Text = bar.money.ToString();
label1.Text = bar.FuncX().ToString();
}
My question is whether or not I could, say, call FuncX without needing the bar. in front of it? I know in C++ if you include a header file with a function in it, you can call it without the need for a prefix, so I was wondering if C# had something similar.
No. There is nothing of that sort now. C# 6 however will bring this future hopefully as Simon Whitehead. For example after importing Console using some magic syntax, you can just use WriteLine() instead of Console.WriteLine(). But not now.
For now, only namespaces can be imported using an using statement, which will give you access to all (please don't argue about access modifiers lol) the classes or whatever inside that namespace.
AFAIK you can not include/alias static methods or fields from other types so that you can use them without specifying the type in c#. All there is is the using directive to rename types and there are extension methods. Extension methods are static methods disguised as instance methods of other types.
If you really don't want the type name in front of it, you'll have to write a wrapper method.
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