C# Errors - File wont compile - c#

I have a code that I'm meant to compile into a .DLL file (it's for the game Call of Duty: Modern Warfare 3). However, it wont compile. Any ideas? Thanks!
using MapEdit;
using Addon;
using System;
namespace mp_terminal_cls
{
public class mp_terminal_cls : MapEdit
{
public mp_terminal_cls()
{
}
createfloor(new Vector(2263f,4406f,286f),new Vector(2958f,4147f,286f));
public override void OnMapChange()
{
base.OnMapChange();
}
}
}
I get 7 errors, the problem is the original code was exactly the same. I only added 2 new lines of code. Here is the errors:
Sorry I'm quite new to C# I only have about 2 months experience with VB.

1) Move the call to createfloor either into the constructor's body or OnMapChange's body (from your code, we can't tell which one you need):
public mp_terminal_cls()
{
createfloor(new Vector(2263f,4406f,286f),new Vector(2958f,4147f,286f));
}
or
public override void OnMapChange()
{
createfloor(new Vector(2263f,4406f,286f),new Vector(2958f,4147f,286f));
base.OnMapChange();
}
2) The base class MapEdit doesn't seem to have a OnMapChanged method.
As a side-note, your classes and namespaces should have distinct names, to avoid ambiguity issues.

There are essentially two errors
MapEdit is a namespace but is used as a type usually means that you
have a class called MapEdit inside a namespace called MapEdit.
Refer to it as MapEdit.MapEdit.
The rest are caused by the call to CreateFloor not being inside a
function. I assume that it should exist inside the constructor so move it inside

Related

Is there a reason for giving the class holding Main() a namespace in C#?

After attempting to research C# namespaces further (coming from a c++ background) I think I understand the purpose of namespaces in general - to organise classes for the user, and to avoid conflicts. This practise, I imagine, still holds just as true for programs as it does for libraries.
What I don't understand is why exactly classes housing the Main() function would need to be part of a namespace.
I can't imagine that the main function would need to be called elsewhere for any reason, so organisation and conflict prevention ought not to be the reason.
Is it simply to show other developers what namespace to use throughout the rest of the program's classes? Or is there some deeper reason for it that is going over my head?
What I don't understand is why exactly classes housing the Main() function would need to be part of a namespace.
For sake of simplicity, we're going to assume that the class that contains Main() is called Program.
The Program class does not need to be in a namespace. For example, explicitly declaring the class:
// Program.cs
public class Program {
public static void Main(string[] args) {
System.Console.WriteLine("hi");
}
}
namespace MyNamespace {
public class Data {
public int Val {get;set;}
}
}
or using Top Level Statements
// Program.cs
System.Console.WriteLine("hi");
namespace MyNamespace {
public class Data {
public int Val {get;set;}
}
}
SharpLab (the links above) shows you what the compiler will output, and in both the Program class doesn't exist inside a namespace, even though other classes will.
And for the record, this is not limited to the Program class. You can put any/all of your types in the "global" namespace. You just lose the "categorization" benefit of namespaces.
I can't imagine that the main function would need to be called elsewhere for any reason
I'd agree. Normally you'd let the .Net runtime call your Main method. I'm sure you can think of some reason to do so, but really that's up to the architecture of your application. One maybe valid use case would be automated testing with a testing framework (xUnit, MSTest, etc) in a sibling assembly.
Now, say you did want to call the Main method yourself, as long as the Fully Qualified Type doesn't conflict with something else, you can still call it just like normal.
public class Program
{
public static void DoThing() { }
}
namespace MyNamespace
{
public class Data
{
public void ActivateDoThing() => Program.DoThing();
// or, if you run into a conflict
public void ActivateDoThing() => global::Program.DoThing();
}
}
Is there a reason for giving the class holding Main() a namespace in C#?
This is due to the editor you're using. Except for the Top Level Statements feature, when you create a new project with the "Console Application" template, it will have the Program class wrapped in a namespace, which is consistent with creating a new code file for a new class. This is just a decision the authors of the template have chosen, but at least it does follow the rule that every file has a namespace block. Familiarity can enhance readability, even if its inefficient.
That's really the point of the Top Level Statements feature - get rid of all the boilerplate. Technically, you don't need a namespace for the entry point class - so get rid of it. Most of the time, you don't add anything to Program besides the Main method, so don't require the user typing the class or method signatures. Just let the user get to the Main logic as fast as possible and the compiler can generate the rest.
That's really about it. Why is the namespace there? Mostly for consistency. Does it need to be there? Nope, not at all.

Error :A namespace does not directly contain members such as fields or methods

The following is the "Hello World" program that I tried to get it compiled with, the Microsoft .Net compiler, by the command "cs".
Using System
public class csharp1
{
private static void main()
{
console.writeline("yaaannn");
}
}
But I got the error:
CS0116: A namespace does not directly contain members such as fields or methods
that too at (1,1)
I checked out for this error:
Error "A namespace does not directly contain members such as fields or methods"
In the above question the compilation was being done through "Visual studio ". So , I am not sure if the things about "app.config" file hold good here when the compilation is being done through inbuilt compiler and from command prompt.
Then I checked the following question:
"A namespace cannot directly contain members such as fields or methods" in Net.Reflector
But here as we can see there was a variable which was not enclosed inside the braces of a class, however in this code there was no variable which was out of the confinements of a class.
So, I am unable to know what is causing this problem.
I thought I am missing a semicolon after "Using system " but that too threw the same error.
No capital letter in using, ; after System, and Main with capital M, add namespace:
using System;
namespace Test
{
class csharp1
{
static void Main()
{
console.writeline("yaaannn");
}
}
}
The compiler believes that this:
Using System
... is trying to introduce a new member, but that's not in the context of a type, which is why you're getting that slightly confusing error message. C# is case-sensitive (both for keywords and for method names etc). A using directive needs to be using rather than Using, and it needs a semi-colon at the end:
using System;
Your code still won't compile, as:
Your main method should be Main to be an entry point. It's valid (but unconventional) to have a method called main, but then your program won't have an entry point.
console.writeline should be Console.WriteLine
So a minimal change to make it compile would be:
using System;
class csharp1
{
static void Main()
{
Console.WriteLine("yaaannn");
}
}
I'd also advise you to follow .NET naming conventions, which would name your class Csharp1 (or more conventionally Program for the class containing an entry point). For anything non-trivial, you'd also want to put your class in a namespace, although you don't have to.
C# is case-senstive, so:
Using System
public class csharp1
{
private static void main()
{
console.writeline("yaaannn");
}
}
Should be:
using System;
public class csharp1
{
public static void Main()
{
Console.WriteLine("yaaannn");
}
}

Understanding namespaces and their use better

One article about namespaces says
Namespaces are C# program elements designed to help you organize your
programs. They also provide assistance in avoiding name clashes
between two sets of code. Implementing Namespaces in your own code is
a good habit because it is likely to save you from problems later when
you want to reuse some of your code. For example, if you created a
class named Console, you would need to put it in your own namespace to
ensure that there wasn't any confusion about when the System.Console
class should be used or when your class should be used.
Now imagine as in above statement I indeed created a Console class inside my namespace called: myNamespace.
Now at some point when someone wants to use say my library, he/she will have to do:
using myNamespace;
but likely she will need to do
using System;
too.
So we still have a clash. If I type Console, which console am I referring to?
How is this problem solved using namespaces?
PS. extra: also how namespaces work under the hood: I remember somewhere I read compiler just prepends functions for example with namespace to find their definitions?
Is this that? Is namespace really nothing just a means to group code?
If you use both of the namespaces, you will either have to fully qualify the usages(System.Console()), or use namespace/type aliases(Console2) to disambiguate the types.
using Console1 = myNamespace;
using Console2 = System;
public void MyMethod()
{
Console1.Console(); // or myNamespace.Console()
Console2.Console(); // or System.Console()
}
You would not include both using statements.
You choose, so your code looks cleaner:
using System;
public static void Main()
{
Console.WriteLine("I'm here!");
myNameSpace.Console.PopBeer("Mo beer!");
}
for practical purposes, if you have a really long namespace, you can use aliases too:
using System;
using sexyNs = myProject.AwesomeSolution.Helpers;
public static void Main()
{
Console.WriteLine("I'm here!");
sexyNs.Console.PopBeer("Mo beer!");
}
The program will not compile. You need to instantiate your classes like this:
System.Console.WriteLine("hi");
myNamespace.Console y = .... ;
a better solution would be to avoid using names which cause conflicts. Name your Console something else so it's clear which one you use when you need to.
#user200300,already many have given exact code solution to your problem description.But let me try to explain clearly.Namespaces also provide assistance in avoiding names clashes.
For example:Lets say there is a single project called Stackoverflow and it contains two teams say TeamA and TeamB.
namespace Stackoverflow
{
namespace TeamA
{
class classA
{
public static void Print()
{
Console.WriteLine("Print A");
}
}
}
}
namespace Stackoverflow
{
namespace TeamB
{
class classA
{
public static void Print()
{
Console.WriteLine("Print B");
}
}
}
}
Here both the team TeamA and TeamB are trying to modify same class classA.Namespaces have helped in organizing the code in efficient and in proper accessible way.
If you want to access the print method from any team you outside these namespaces or from any class for that matter you would write like
Stackoverflow.TeamA.classA.Print();
Stackoverflow.TeamB.classA.Print();
So above code is cumbersome and lengthy and its not clean.Hence aliases can be used .
using STAP=Stackoverflow.TeamA;
using STBP=Stackoverflow.TeamB();
Now you can access easily.
STAP.classA.print();//TeamA's print method.
Thus a namespace can contain Namespace,Class,Inteface,struct,enum,delegate

Why can't I call an extension method from a base class of the extended type‏?

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();
}
}

Using an extension method defined in nested class

Consider the following code:
1. namespace MyNS {
2. // A class
3. public class MyClass {
4. public string Do() {
5. return string.Blank();
6. }
7. // A nested type
8. protected static class Helper {
9. public static string Blank(this string str) {
10 return String.Empty;
11. }
12. }
13. }
14. } /* namespace */
However line 5 will cause the program not to compile. I know that in order to use extension methods a static class must be created and its enclosing namespace referenced through using directives.
How to achieve this when the static class is a nested class?
It cannot be done. Extensions methods cannot be defined in nested classes.
Although there is not major obstacle to implementing this feature, it does feel rather cumbersome: extension methods inside a nested class seem overkill as they might as well be defined as part of the outer class itself.
Also, it does force you to clearly organized this as extensions to your classes (again, is you must), rather a than part of them.
If you simply want to defined them locally (as in close to other related functionality), you might want to try SLaks' trick of creating the extensions methods inside a nested namespace declaration, making the class inside this new namespace not longer "nested".
You can't. For the method to be an extension method it needs to be in a non-nested class.

Categories

Resources