"Include" a Class in C# - c#

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.

Related

Use Internal Class in C# Harmony Patch

I'm pretty new to c#, and I'm using Harmony patches to make a mod for a video game. The method I'm trying to patch is a private method which takes an internal class instance as a parameter. I've been able to use reflection to handle private methods in a few other patches, but when I try to add the internal parameter, I get a build error saying the class is inaccessible due to it's protection level.
I was trying to use the solution from this question, but I think I'm having some scope issues. Right now, I have something like
using System;
...
using System.Reflection;
using HarmonyLib;
using namespacesFromGame; // Including namespace where the internal is declared
...
namespace MyMod
{
[HarmonyPatch(typeof(GameClass))]
class MyPatch
{
Type MyInternal = typeof(GameClass).Assembly.GetType("GameInternal");
public static bool MethodPatch(GameClass__instance,..., MyInternal myInternal, ...)
{
...
}
}
}
When I try to do this, it tells me The type or namespace name 'MyInternal' cannot be found.
Where should I be putting my MyInternal declaration so it can be used as a parameter to MethodPatch, and so I will also be able to use the myInternal instance in the patch?
In C# you cannot declare the type of a property with another variable.
I see two solutions to this problem.
You can either do this :
using System;
...
using HarmonyLib;
using namespacesFromGame; // Including namespace where the internal is
namespace MyMod
{
[HarmonyPatch(typeof(GameClass))]
class MyPatch
{
public static bool MethodPatch(GameClass __instance,..., object myInternal, ...)
{
...
// do reflexion to access the method, the field and prop the object
}
}
}
This should work; but if you are new to C# the reflection may not necessarily be the easiest thing to do and it can quickly make your code unreadable.
Or do this :
You can publicise (make public) the dll you want to use. If you do this, you will have access to all classes, methods and ect... By doing this you will only have to use the desired type. But, you will have to compile your code in unstable.
For publicise, i found two github repo :
https://github.com/rwmt/Publicise
https://github.com/iRebbok/APublicizer
(you can also create your own but I think that to start it would be better to take one already made)
It will require republishing the assembly each time there is an update if your mod is outdated.
I also create modes on unity games. This is the solution I use and some FrameWork for modding uses to.
I don't know if there are performance impacts of using unstable code and calling private methods.
I advise you this solution, you would get cleaner code and you will have access to code more easily. But that is my personal opinion.

How do properly set up my common C# code so I can access them with a using directive?

I want to be able organize my most common code elements so that they can be "included" with a using statement similar to
using System;
using System.IO;
I am able to do this to a certain extent, but because of C# rules about namespaces and classes, I am unable to access my stuff directly, I always have to add it to a class and then access it by .item.
For example if I make a C# file named MyStuff.cs as follows:
namespace MyStuff
{
public static class MyClass
{
public static int MyCode(...)
{
...
}
}
}
I have to use it in my other code like this:
using MyStuff
...
int result = MyClass.MyCode(...);
...
I would like to be able to just access it like this (without the MyClass):
using MyStuff
...
int result = MyCode(...);
...
But I can't get that to work. I read somewhere that adding the "static" to the class they are in then the dot notation would not be needed, but that does not appear to be true.
Can anybody explain how to do this, or am I stuck with the extra layer?
Thanks!
I don't think it can be done.
In order to something to be accessed directly from within a namespace, it has to be an object. Functions cannot be directly put inside a namespace.
You can achieve what you want by making use of extension method by writing an extension method for instances of the 'Object' class (which is more of a hack). But you will still have to invoke it this way, this.MyCode().
Another solution is to have a superclass where you have this function MyCode() and inherit the place where you are going to use MyCode() from there but I am pretty sure that you have already considered something which is as basic as that.

C# / C++ - Methods under namespace

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.

Using "helper classes" in winforms, C#

I tried to ask a question yesterday but it was seemingly too vague. Here's another try.
In the past, I have used some winforms/VB.Net classes with functionality for, say, working on text strings, for file operations, or for database handling, like clsStrings, clsIO and clsDB. The idea was that these classes did everything related to the subject, so that clsStrings would have a method called "filterString", removeCertainChars" etc.
In the old winforms application, I simply wrote Imports clsStrings when I needed to access a method. Throughout the .vb file, I could then write something like
str = filterString(TextBox1.Text)
I now try to get the same functionality in a new winforms app in C#. The only thing I get to work is creating a variable for the class:
clsStrings clsstrings = New clsStrings();
...and then later in the code:
str = clsstrings.filterString(TextBox1.Text);
So I guess what I would want is the ability to use a using statement for these "helper classes" (is there a better word for them?) so that I wouldn't have to write the variable name all the time. (Just like when Intellisense discovers that a namespace is missing and asks if I want to have a using statement for, say, System.Data so I can write "DataTable" instead of having to write "Data.Datatable" all the time.)
I suspect I would need to put these class files in a separate folder or so, but that would be totally fine. I just want some structure to my app.
I hope this is clearer.
Thanks for any input!
Well, the difference is that now you are working with OOP principles.
What you could do to be closer to what you were used to is to build static classes for the helper class, maybe even turn them into extension methods.
Example:
public static class ClsStrings
{
public static string FilterString(this string stringToFilter) { return something; }
}
Then you could call it like this:
string filteredString = TextBox1.Text.filterString();
or
string filteredString = ClsStrings.filterString(TextBox1.Text);
Extension methods is the way to go here. Using these you can basically exten String class with your own methods and do something like Sting.filterString();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx

C# global module

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

Categories