Programming question: function library in C#
Yes, I know, C# doesn't do function libraries.
Yes, I also know that you can emulate a function library by creating a static class with the functions as members, like this:
Code:
public static class Utils {
public static int MyIntFunction(int coolParam)
{
//do stuff
}
}
This issue I have with this approach is that I always have to type out the name of the static class:
Code:
[...]
int myInt = Utils.MyIntFunction(42);
[...]
Is there any way so that I don't have to type out Utils all the time?
Re: Programming question: function library in C#
Would it make semantic sense, for whatever the name and purpose of your function actually is, to call it like this?
Code:
int myInt = 42.MyIntFunction();
If so, you could define it as an extension method. All it would take is adding "this" in front of the function's first parameter, so your example would become
Code:
public static class Utils {
public static int MyIntFunction(this int coolParam)
{
//do stuff
}
}
Re: Programming question: function library in C#
I'm not sure if I understand.
In other languages like C++ or Delphi you can create namespaces/units/whatever that simply define methods. Then by declaring that you use the namespace you can just call the method. While in C#, if you want to call, say, Mathf.Max you have to do it like this:
Code:
public class myClass {
public int myFunc(int param)
{
return Mathf.Max(10, param);
}
}
My question is if it is possible to arrive at something like this:
Code:
using Mathf //I know this doesn't work
public class myClass {
public int myFunc(int param)
{
return Max(10, param); //calls Mathf.Max
}
}
Re: Programming question: function library in C#
I was suggesting a possible alternative. In C# if you define a function like this:
Code:
public static class Utils {
public static int Add(this int i, int j) {
return i + j;
}
}
Then you can call it like this:
Code:
int sum = 10.Add(12); // calls Utils.Add(10, 12)
I just did a little bit of searching, though, and exactly what you asked is actually possible.
Code:
using static Mathf; // This does work
public class myClass {
public int myFunc(int param)
{
return Max(10, param); //calls Mathf.Max
}
}
Re: Programming question: function library in C#
Yeah, I was about to suggest the "using" directive--you can specify any class with that and it will allow you to use functions from that class without qualification. It's usually used for system classes in the .NET framework but you can use it for your own as well.
Re: Programming question: function library in C#
The "using" statement will work for bringing in references like that. The thing to watch out for is overlap with other namespaces that you might want to use in the project, depending on the environment you are coding in you may get a warning that about an ambiguous namespace or reference if you have another reference that has a function with the same name.