Can I Split my C# local method across multiple files? - c#

I have this:
(note: this is not the main file, that's why it doesn't have the Main method)
namespace MJeC_Sharp
{
class Program
{
public static void Game()
{
Move();
void Move()
{
}
}
}
}
Is there a way to have void Move() on another file while keeping the conveniences of not having to pass variables to it?

No, local methods have to be written inside the text of their outer method and there is no way to split a single method into multiple files.
It is possible to split the same class into multiple files - so a non-local method can be easily written in a separate file - Can I split my C# class across multiple files?.
Note that in C/C++ you can do something like that by using pre-processor's #include statement - C# does not support that, but if you really need such functionality and your team is comfortable with modifying build you can try using C preprocessor to do includes before compiling code with C#. Note that the source code will no longer pass C# syntax checks (as included methods will be missing) - so it probably not useful for human readable code (maybe useful in some code gen cases ).

Related

Is it possible to keep precompiled symbols in C# assemblies for use in a referencing program?

I know that the C# preprocessor will generally eliminate the precompiled symbols. Can the rule be broken a bit?
For example, I have a C# dll A, which I wanna use in another C# program B. In B I have different precompiled symbols X, Y, Z. If X is defined, I need a version of A. Else if Y is defined, I need another version of A. And similar for Z. To implement this, I want to write precompiled directives in A's source code, like
public static class MyClass
{
public static void MyMethod()
{
#if X
DoX();
#elif Y
DoY();
#elif Z
DoZ();
#else
DoWhatever();
#endif
}
}
I hope these conditions don't disappear during A's compiling and B can take use of them. Is it possible? Or what should I do to work around this?
Thanks in advance.
EDIT
Some background information. B is a Unity3D Game, and A is a common library we want to use across different games. So Both A and B relies on the assembly UnityEngine.dll. Then there is various precompiled symbols defined by U3D to indicate the current build platform, the engine's version and etc, which I want to take use of in both A and B.
Being that B is a Unity3D game what you need to do is just compile your 3 different versions of A and put them in the appropriate default folders for the plugin inspector.
Instead of X, Y, and Z, lets say we have UNITY_EDITOR, UNITY_WSA, and UNITY_IOS.
public static class MyClass
{
public static void MyMethod()
{
#if UNITY_EDITOR
DoX();
#elif UNITY_WSA
DoY();
#elif UNITY_IOS
DoZ();
#else
DoWhatever();
#endif
}
}
You would need to make 3 copies of A.dll each compiled with the different setting set.
Once you have your 3 dll's you just need to put them in the correct folders in your project to be set to the proper build types automaticly. Your file structure should look like
Assets/Plugins/Editor/A.dll
Assets/Plugins/WSA/A.dll
Assets/Plugins/iOS/A.dll
You don't have to use that structure, but using those folders make them automatically get picked up by the inspector for the correct build types.
In general, you define compiler constants on a project basis. So if your shared assembly defines X and you compile it, it only contains the call to DoX(). Then you compile the actually consuming application where you define Y, but that won't affect the shared assembly.
However, compiler constants can be passed to the compiler using the command line or using XAML, and then apply to all projects that are built at the same time.
How to do so is explained in Is There anyway to #define Constant on a Solution Basis? and MSDN: How to: Declare Conditional Compilation Constants.
So that might be an option: declare them solution-wide and compile the solution as a whole. Do note that your shared assembly then only contains the call corresponding to the constant(s) defined at compile-time: you can't share that assembly with different executables compiled with different constants, because only DoX() will be called if X was declared at compile-time.
Or, rather, you dump this idea altogether and implement the proper design pattern, so the proper method will be called depending on what the caller wants, not who the caller is.
This may mean you should simply expose DoX(), DoY() and DoZ() to the caller, or let MyMethod() do something based on a passed (enum) variable, or something using a strategy pattern.
That being said, there may be reasons to do what you're trying to do, for example not leaking implementation details to competing companies who use your application.

Alternative to global variables on C#

I'm currently learning C# having been most familiar with Ruby previously, and I was writing some code which required a bool variable to be accessed from multiple places, to check and/or set the state. In Ruby this would be a piece of cake, just declare $my_global_variable = false (or whatever). Having looked this up I was successfully able to replicate this in C# by declaring the following:
public class GlobalVariables
{
public static bool exampleGlobalVariable;
}
And then accessing GlobalVariables.exampleGlobalVariable whenever I need to. However everything I read about global variables in C# suggests that they're considered problematic and if you implement them you're a terrible person.
So my question is, what alternatives are there? Passing variables back and forth is messy to my eye and sometimes it's not even possible - if a method is already passing back a variable, for example.
Is there another way of achieving this functionality that's neat and idiomatic for C#?

Removing preprocessor branching in C#

I am refactoring some source code and got a task to remove preprocessor compiling. I have now searched internet for some days, but haven't found any good idea how to do that. I am also quite new to C#.
So the problem is following, I have different interfaces (classes) for every device and "ControlLogic" class needs to use only one of them at the time. Device is chosen on program run-time.
So far "device" variable (also used globally) is used in a lot of places and considering renaming that doesn't make sense to me. Also all device interfaces (classes) are derived from base class, but interface classes does implement different methods for them.
public class ControlLogic
{
#if FIRST_DEVICE
public FirstDeviceInterace device = null;
#elif SECOND_DEVICE
public SecondDeviceInterface device = null;
#elif THIRD_DEVICE
public ThirdDeviceInterface device = null;
#endif
// One example method
public void startDevice()
{
if (device != null)
{
#if (FIRST_DEVICE || SECOND_DEVICE)
device.startDevice();
#endif
#if THIRD_DEVICE
device.startThirdDevice();
#endif
}
}
// More code.....
}
So what is the best way to remove preprocessor compiling?
I've faced with a similar task a few months ago: large C# code base and extensive preprocessor directives usage. Manual refactoring looked like a long boring monkey job there.
I've failed with unifdef, sunifdef and coan C tools because of C# syntax specifics like #region and some others. In the long run I've made my own tool undefine. It uses regexp to parse the preprocessor directives and sympy python library to simplify logical expression. It works good for me on large 10M lines code base.
I understand that the three device types do not have a common base class or interface. You cannot just pick one of the three at runtime and type all variables with a base type.
Here are a few options:
Find a way to a a common base type.
If you cannot modify the classes (or it would be inappropriate for some reason) write a wrapper. That wrapper can have any structure you like. You could have one wrapper per device class with a common base type.
Use dynamic. This can be a quick fix at the cost of less tooling help (less autocompletion, less documentation at hand, less quick static error checking).
Using #if to solve this problem is very unusual. It is problematic because the amount of testing to even make sure the code compiles has now tripled. You also need multiple binaries.

How to hide Non-CLS compliant code from projects using other languages?

This question is more out of curiosity than a project requirement or a problem.
I have a Non-CLS compliant code in one language (say C#), and I need to use it like that only in my current language (across projects, so making internal is not a choice), and at the same time want to allow other languages (say VB) to be able to call the conflicting implementations without generating compile time error.
For instance,
//C#
public class SecurityService
{
....
public void Print()
{
Console.WriteLine("print"); //This method prints Service Name in lower case
}
public void PRINT()
{
Console.WriteLine("PRINT");//This method prints service name in UPPER case.
}
}
'VB.Net
Module ServiceReader
Sub Main()
Dim service As New SecurityService()
service.print() 'Compile time error: print is ambiguos
End Sub
End Module
Problem: I need to avoid the compile time error here by somehow hiding one of my 'print' methods from cross language projects (allowing C# projects to call the desired implementation).
Thanks for your interest.
A language like VB.NET offers no escape around its fundamental syntax rule that identifiers are case insensitive. It is not hard to solve, you can simply write a little static adapter method in a case sensitive language like C# that makes the call.
public static class Interop {
public static void Print2(SecurityService obj) {
obj.PRINT();
}
}
You can completely shove it under the doormat by making it an extension method, assuming the language supports it. There will be no actual runtime overhead when the jit optimizer is done with it.
I'd suggest you make the non-CLS compliant methods/properties internal, but then make another class that isn't CLS compliant to call that stuff and mark that class as [CLSCompliant(false)]
I don't see the point of trying to make this work. My advice would be to avoid the problem in the first place and stop writing non-compliant code, especially if you are planning on supporting different languages. You have total control over the module here so you shouldn't actually need any fancy hacks.

Using Extensions: Weighing The Pros vs Cons

Recently I asked a question about how to clean up what I considered ugly code. One recommendation was to create an Extension Method that would perform the desired function and return back what I wanted. My first thought was 'Great! How cool are Extensions...' but after a little more thinking I am starting to have second thoughts about using Extensions...
My main concern is that it seems like Extensions are a custom 'shortcut' that can make it hard for other developers to follow. I understand using an Extension can help make the code syntax easier to read, but what about following the voice behind the curtain?
Take for example my previous questions code snippet:
if (entry.Properties["something"].Value != null)
attribs.something = entry.Properties["something"].Value.ToString();
Now replace it with an Extension:
public static class ObjectExtensions
{
public static string NullSafeToString(this object obj)
{
return obj != null ? obj.ToString() : String.Empty;
}
}
and call using the syntax:
attribs.something = entry.Properties["something"].Value.NullSafeToString();
Definetely a handy way to go, but is it really worth the overhead of another class object? And what happens if someone wants to reuse my code snippet but doesn't understand Extension? I could have just as easily used the syntax with the same result:
attribs.something = (entry.Properties["something"].Value ?? string.Empty).ToString()
So I did a little digging and found a couple of articles that talked about the pros/cons of using Extensions. For those inclined have a look at the following links:
MSDN: Extension Methods
Extension Methods Best Practice
Extension Methods
I can't really decide which is the better way to go. Custom Extensions that do what I want them to do or more displayed code to accomplish the same task? I would be really interested in learning what 'real' developers think about this topic...
Personally I think the "problems" of extension method readability are vastly overstated. If you concentrate on making your code easy to read in terms of what it's doing, that's more important most of the time than how it's doing it. If the developer wants to trace through and find out what's actually happening behind the scenes, they can always click through to the implementation.
My main problem with extension methods is their discovery method - i.e. via a specified namespace instead of a specified class. That's a different matter though :)
I'm not suggesting that you put in extension methods arbitrarily, but I would seriously consider how often you need to know how every expression in a method works vs skimming through it to see what it does in broader terms.
EDIT: Your use of terminology may be misleading you slightly. There's no such thing as an "extension object" - there are only "extension methods" and they have to exist in static types. So you may need to introduce a new type but you're not creating any more objects.
[OP] Definetely a handy way to go, but is it really worth the overhead of another class object?
No extra class object is created in this scenario. Under the hood, extension methods are called no differently than a static method. There is an extra metadata entry for the extension method container but that is pretty minimal.
[OP] And what happens if someone wants to reuse my code snippet but doesn't understand Extension Objects?
Then it would be a good time to educate them :). Yes, there is the risk that a new developer may not be comfortable with extension methods to start. But this is hardly an isolated feature. It's being used more and more in all of the code samples I'm seeing internally and on the web. It's something that is definitely worth while for a developer to learn. I don't think it fits into the category of "to esoteric to expect people to know"
The only serious weirdness to deal with in Extension methods are:
They do not have to cause a null reference exception if the left hand side (the object on which it appears you are invoking a method) is null.
can sometimes be useful, but is contrary to expectations as such should be used with extreme caution.
They are not accessible through reflection on the classes/interfaces to which they apply.
generally not a problem, but worth keeping in mind.
Name collisions with other extension methods involve a lengthy resolution rule sequence
if you care the sequence is to prefer:
Extension methods defined inside the current module.
Extension methods defined inside data types in the current namespace or any one of its parents, with child namespaces having higher precedence than parent namespaces.
Extension methods defined inside any type imports in the current file.
Extension methods defined inside any namespace imports in the current file.
Extension methods defined inside any project-level type imports.
Extension methods defined inside any project-level namespace imports.
[OP] And what happens if someone wants to reuse my code snippet but doesn't understand Extension Objects?
The extension methods will not show in the intellisense for the object if the assembly that implements them is not references in the project. Your code snippet will also not compile. That could potentially create a bit of a confusion to the other developer.
If the extension method assembly is referenced, it will show in the intellisense, but it will be not mentioned in the documentation for the object. This could potentially cause a bit of confusion as well.
However, as #JaredPar mentioned, the extension methods as a technique are used more and more and I would expect most of the C# programmers to know about them. Thus, I wound't be too worried about any potential confusion.
C# Extensions is an additional "tool" provided by .Net in order to help you write your code a little bit nicer. Another advantage of them is, that they handle null. Although they seem very usable, I try to use them only in certain cases that will really tidy up my code, because they are not standard coding methods and they stand a little bit seperate from other classes as they have to be in static classes and are static themselves.
Let's say their implementation is a little bit untidy, but their use is made tidier.
It is also important to mention that they only exist in C# and VB.Net (Java doesn't have Extensions). Another important fact is that Extensions have no priority over standard methods, meaning that if a method is implemented in a class with the same name as an extension method on the same class, then the first method is the one that will be called and not the extension method.
Below there are three cases where I often use them, why I use them and alternative solutions that would solve the same problem:
1. To implement specific methods for generic classes:
I have a generic type, let's say a collection List<T>. I want to do a method that applies only to a specific kind of list. Let's say a method that creates a union from a list of strings using a seperator
("A", "B", "C", " sep " --> "A sep B sep C"):
public static string union(this List<string> stringList, String seperator)
{
String unionString = "";
foreach (string stringItem in stringList) {
unionString += seperator + stringItem; }
if (unionString != "") {
unionString = unionString.Substring(seperator.Length); }
return unionString;
}
In case I didn't want to use an extension, I would have to create a new class "StringCollection : List<string>" and implement my method there. This is mainly not a problem and it is actually better in most cases, but not in all cases. If for example you are receiving all your data in lists of strings in many cases, you don't have to convert those lists in StringCollections each time you want to use union, but use an extension instead.
2. To implement methods that need to handle null:
I need a method to convert an object to a string without throwing an exception in case the object is null
public static String toStringNullAllowed(this Object inputObject)
{
if (inputObject == null) { return null; }
return inputObject.ToString();
}
In case I didn't want to use an extension, I would have to create a class (probably static), for example StringConverter, which will do the same job, with more words than a simple myObject.toStringNullAllowed();
3. To extend value types or sealed classes:
Value types such as int, float, string, etc as well as sealed classes (classes that cannot be inherited) cannot be extended through inheritance. Below you can see an example of extending integers to be able to be converted to x-digit Strings (for example integer 34, digits 5 --> "00034"):
public static String toXDigit(this int inputInteger, int x)
{
String xDigitNumber = inputInteger.ToString();
while (xDigitNumber.Length < x) { xDigitNumber = "0" + xDigitNumber; }
return xDigitNumber;
}
Again an alternative solution would be a static class (like a toolbox), let's say "Math".
In that case you would write: Math.toXDigit(a, x);
While with the extension method: a.toXDigit(x);
The extension method looks better and is more understandable, like speaking English
To conclude, I guess the disadvantage of extensions is that their implementation is seperated from standard classes and looks a little bit odd or difficult to programmers that are not used to them, while their advantage is that they offer a more understandable, tidier and encapsulated use of the language.

Categories