I'm new in Unity. My question isa, is it possible to create function files, without constructor and other stuff? In flash actionscript 3 it's look like this:
package util
{
public function getRandomNumber(minQ:Number = 0, maxQ:Number = Number.MAX_VALUE):Number
{
return minQ + Math.random() * (maxQ - minQ);
}
}
Is it possible to do somthing similar like this?
No, it is impossible in C#. I suggest you learn about Extension Methods and Partial classes.
You can use static classes and singletons as well, but try to avoid the temptation to access it from every part of your project - it will be difficult to modify and refactor it in the future.
You cannot create a global function, but you can create a static method in a static class:
namespace MyNamespace
{
public static class Util
{
public static double GetRandomNumber(..) { ... }
}
}
and use it like
var myNumber = Util.GetRandomNumber(...);
The important part here is that the method is static, which means that you don't need an instance of the class to call it. The static class means that it is impossible to create an instance of that class.
Related
Am new to C#, but have a plenty of experience of VB.net, now my issue is that there are no modules in C# and i need to define a class which is accessible in all classes and i don't know how to do it.
For example I have a "classProject" and I need to make it accessible everywhere, so in vb.net , I will define it in module like below.
Module ModuleMain
Public tProject As New ClassProject
End Module
Now, I need to do same in C#.
Thanks in advance.
You can do this in your case:
namespace MyProject
{
public static class classProject
{
int myIntvar = 0;
string myStringvar = "test";
}
}
And you can use this static class in your other classes like:
public class Test
{
int intTest = classProject.myIntvar; //will be 0
string stringTest = classProject.myStringvar; // will be test
}
You can use the variables in the static class since a static variable shares the value of it among all instances of the class. When you create multiple instances of classProject class, the variables myIntvar and myStringvar are shared across all of other classes in your project. Thus, at any given point of time, there will be only one integer and one string value contained in the respective variable's.
It sounds like you're looking for a static class. You can reference the access modifiers here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers
I think you need to extends your other classes to class father (ClassProject) And you can access to it with youur children classes.
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
see more
I have a solution with a "Common" project. This "Common" project is used by other projects in the solution.
Within this "Common" project, I have a "Utilities" folder with several different utility classes, for example, "CsvUtilities.cs" and "JsonUtilities.cs". Assume that I could have many classes like this, and that all methods in these classes are pure functions. Based on this, it would make sense for these classes and methods to be static. Then from other projects I can import the common project and do things like:
CsvUtilities.StaticCsvMethod();
JsonUtilities.StaticJsonMethod();
This works and I think this is relatively normal.
Now the complication is that I want to create a hierarchy structure to access the static utility methods. I want to be able to type "Utilities." in the IDE and have intellisense show all existing utility classes, followed by all methods within that utility class.
So the code that I want would look like this:
Utilities.Csv.StaticCsvMethod();
Utilities.Json.StaticJsonMethod();
I implemented this idea by doing the following:
public static class Utilities
{
public static CsvUtilities Csv { get; } = new CsvUtilities();
public static JsonUtilities Json { get; } = new JsonUtilities();
}
However, there is a big problem with this solution. For this to work, the various utility classes and their methods must no longer be static, which is awkward for utility classes/methods.
I was not able to find an example of someone else doing something like this. What is the most reasonable way for me to use this "Utilities." structure while also keeping the utility classes/methods static?
You can use namespaces (or nested classes) to nest your calls like that. See following example
namespace Utilities
{
public static class Json
{
public static void StaticJsonMethod()
{
// Do something
}
}
}
you can call that method using Utilities.Json.StaticJsonMethod().
To add another level, you just append the "category" to the namespace:
namespace Utilities.Formats
{
public static class Json
{
public static void StaticJsonMethod()
{
// Do something
}
}
}
you can call that method using Utilities.Formats.Json.StaticJsonMethod()
You can have Utilities.Json.StaticJsonMethod(); if you nest static class Json inside Utilities
public static class Utilities
{
public static class Json
{
public static void StaticJsonMethod() { }
}
}
So I have a static class lets say its called Worker, and lets say
I have a method inside it called Wait(float f) and its all public so I can acess it anywhere like so:
Worker.Wait(1000);
Now what I am wondering is there any way I can define some kind of unique
special methods so I could just do it short like this:
Wait(1000);
(Without having it in the class I would use it in) ?
With C# 6 this can be done. At the top of your file you need to add a using static Your.Type.Name.Here;.
namespace MyNamespace
{
public static class Worker
{
public static void Wait(int msec)
{
....
}
}
}
//In another file
using static MyNamespace.Worker;
public class Foo
{
public void Bar()
{
Wait(500); //Is the same as calling "MyNamespace.Worker.Wait(500);" here
}
}
No, you cannot have methods that are not part of a class in C#.
No, you can not, Methods belong to a class, if you do Wait(1) is because you are in a class where that method is defined (or is the parent class)
Edit...
As commented that was true up to C# 5, this can be done in C# 6 now it can be done importing statically some classes...
take a look at Scott Chamberlain"s answer here and link to MSDN
I'm trying to refactor a method that parses through a file. To support files of arbitrary size, the method using a chunking approach with a fixed buffer.
public int Parse()
{
// Get the initial chunk of data
ReadNextChunk();
while (lengthOfDataInBuffer > 0)
{
[parse through contents of buffer]
if (buffer_is_about_to_underflow)
ReadNextChunk();
}
return result;
}
The pseudo code above is part of the only public non-static method in a class (other than the constructor). The class only exists to encapsulate the state that must be tracked while parsing through a file. Further, once this method has been called on the class, it can't/shouldn't be called again. So the usage pattern looks like this:
var obj = new MyClass(filenameToParse);
var result = obj.Parse();
// Never use 'obj' instance again after this.
This bugs me for some reason. I could make the MyClass constructor private, change Parse to a static method, and have the Parse method new up an instance of Parse scoped to the method. That would yield a usage pattern like the following:
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local instance in the Parse method.
Since this class only has two methods; Parse and (private) ReadNextChunk, I'm wondering if it might not be cleaner to write Parse as a single static method by embedding the ReadNextChunk logic within Parse as an anonymous method. The rest of the state could be tracked as local variables instead of member variables.
Of course, I could accomplish something similar by making ReadNextChunk a static method, and then passing all of the context in, but I remember that anon methods had access to the outer scope.
Is this weird and ugly, or a reasonable approach?
This maybe suitable more to code review.
However, these are my comments about your design:
I don't think it will matter much about obj instance only used once. If you bugged with it, there are 2 ways to trick it:
Use of another method such as:
public int Parse()
{
var obj = new MyClass(filenameToParse);
return obj.Parse();
}
Make the MyClass implement IDisposable and wrap it in using statement. I don't recommend this since usually IDisposable has logic in their Dispose() method
I think it is better to make your MyClass accept parameter in Parse to Parse(string fileNameToParse). It will make MyClass as a service class, make it stateless, reusable and injectable.
Regarding impact to static class. First it add coupling between your consumer and MyClass. Sometimes if you want to test / unit test the consumer without using the MyClass parser, it will be hard / impossible to mock the MyClass into something you want.
All you need is a static parse method that creates an instance, much like what you suggest in your question
public class MyClass
{
// your existing code.... but make the members and constructor private.
public static int Parse(string filenameToParse)
{
return new MyClass(filenameToParse).Parse();
}
}
then
just use it like you suggest...
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local
instance in the Parse method.
You don't need a static class to be able to leverage static methods. For example this works fine:
public class MyClass
{
public static string DoStuff(string input)
{
Console.WriteLine("Did stuff: " + input);
return "Did stuff";
}
}
public class Host
{
public void Main()
{
MyClass.DoStuff("something");
}
}
Is there any way to call a function that is inside of a namespace without declaring the class inside c#.
For Example, if I had 2 methods that are the exact same and should be used in all of my C# projects, is there any way to just take those functions and make it into a dll and just say 'Using myTwoMethods' on top and start using the methods without declaring the class?
Right now, I do:
MyClass.MyMethod();
I want to do:
MyMethod();
Thanks,
Rohit
Update for 2015:
No you cannot create "free functions" in C#, but starting with C# 6 you'll be able to call static functions without mentioning the class name. C# 6 will have the "using static" feature allowing this syntax:
static class MyClass {
public static void MyMethod();
}
SomeOtherFile.cs:
using static MyClass;
void SomeMethod() {
MyMethod();
}
You can't declare methods outside of a class, but you can do this using a static helper class in a Class Library Project.
public static class HelperClass
{
public static void HelperMethod() {
// ...
}
}
Usage (after adding a reference to your Class Library).
HelperClass.HelperMethod();
Depends on what type of method we are talking, you could look into extension methods:
http://msdn.microsoft.com/en-us/library/bb383977.aspx
This allows you to easily add extra functionality to existing objects.
Following on from the suggestion to use extension methods, you could make the method an extension method off of System.Object, from which all classes derive. I would not advocate this, but pertaining to your question this may be an answer.
namespace SomeNamespace
{
public static class Extensions
{
public static void MyMethod(this System.Object o)
{
// Do something here.
}
}
}
You could now write code like MyMethod(); anywhere you have a using SomeNamespace;, unless you are in a static method (then you would have to do Extensions.MyMethod(null)).