It's extremely lazy, but I'm wondering if it's possible to have two names point to the same static class in essence.
I have a long and descriptive static class name BusinessLogicServiceUtility (as example) and it's looking rather long-winded in code.
I'd love to use BLSU as an alternative, so I tried extending the long class with my short class name:
public static class BLSU : BusinessLogicServiceUtility
{
}
Which probably looks noob but as it turns out, it doesn't work.
It looks as though I could wrap each method in the long class with a method inside the short class, but there's a lot of methods, which makes maintaining it a pain and circumvents the whole laziness goal.
Is there a way of assigning two names to one static class, or some other method simply "extending" a static class?
You can create an alias for a type:
using BLSU = Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
BLSU.SomeStaticMethod();
With C# 6 you can even go further - access static members of a type without having to qualify type name at all:
using static Your.Namespace.BusinessLogicServiceUtility;
Accessing members of type:
SomeStaticMethod();
Further reading: using Directive (C# Reference)
In addition, you can use using static that will allow you to use the methods without prefixing them with the class at all:
at the top of the file :
using static BusinessLogicServiceUtility;
and say you have a method public static DoLogicThings() in your static class, you can access it directly now:
public void SomeMethod()
{
DoLogicThings();
}
this was added in C#6.
Related
I was unclear in an earlier question I ask so I will try to be more explicit.
Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?
Here is how I would like to use it:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
There are some fundamental reasons why you can't do that directly:
Static method calls are bound at compile-time
Static calls are not inherited - they are tied to the class that defines them
There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same
Since your signature is the same for every static method, you could store a Action in the dictionary instead:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
then you can call the Action directly:
void Start()
{
StaticMap.dictionary[Type.1]();
}
It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.
If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.
However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.
If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.
One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:
container.Register(Component.For<ISomeInterface,SomeClass>));
Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.
Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.
Instead of having the entire class as static, create a Singleton instance.
public class Foo
{
public static Foo _Foo;
public Foo()
{
_Foo = this;
}
}
Then you may add it to your list, and also inherit from Interfaces, etc.
Reading and messing around to understand static classes and static methods and their differences with non static methods and their usage which i still don't get except maybe for the Main method which must not be made an instance(object) of a class.
Why if i try to use:
using static System.ApplicationId;
public class Program
{
static void Main()
{
Copy(SOMETHING)// Copy method doesn't exist
}
}
Then try to use a method from ApplicationId like Copy();
The IDE? can't find the method?
Doing the same with:
using static System.Console;
public class Program
{
static void Main()
{
Writeline("Hello"); // OK
}
}
Then try to find a method from Console like WriteLine();
It can find it and i can use it.
Why does that happen?
My understanding is That those are both static members? Isn't that the reason why i cant make instances of those 2 classes? Yet i can use the methods in the second example but not in the first one since it seems that it doesn't let me (error: copy() doesn't exist in the current context...).
The short answer is that you wouldn't use the static keyword in a using statement for non-static namespaces like System.ApplicationId
To use methods on a non-static (instance) class, you have to first make an instance of it using new. The tl;dr part followsTo avoid having to write out the namespace prefix System. every time you want to refer to ApplicationId, you can add
using System;
and then in the class, you can get to the someMethod() method with:
new ApplicationId().someMethod();
Now let's talk about static:
Before C# version 6, you just couldn't use a using statement on a static class, so to get access to a static method like
System.Console.WriteLine()
you'd first add the non-static parent (System) with
using System
and then refer to the static method using the namespace
Console.WriteLine
With the using static syntax, you add the 'Console.' part of the namespace once per class on the using statement like so:
`using static System.Console;`
and then you can use WriteLine() instead of Console.WriteLine. I have to guess that the WriteLine() method has got to be the most common use case for this functionality.
If you check out https://msdn.microsoft.com/en-us/library/system.console%28v=vs.110%29.aspx it shows that System.Console is a static class, so using static is appropriate there.
However, System.ApplicationId is non-static (see https://msdn.microsoft.com/en-us/library/system.applicationid%28v=vs.110%29.aspx) so you can't use using static.
The answer is simple, the methods in ApplicationId are not marked as static.
Let's see the difference between static and instance methods:
Static method:
Console.WriteLine();
******* *********
^ ^
class method
name name
Instance methods:
Random aRandomObject = new Random();
aRandomObject.Next();
************* ****
^ ^
name of an method
instance of name
Random
As you can see here, you need an instance of that class in order to use non-static methods. But for static methods, you don't need an instance.
The using static directive allows you to omit the class name when you call a static method.
"But why doesn't it allow us to call instance methods like this?" you asked. As I have said above, you need an instance to call instance methods. If you only write the method name to call the method, how can the compiler know what instance do you want to call it on?
ApplocationId is not a static class, so you need to create an instance of it.
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.
Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
And I use this in obvious ways like
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
My question is: Why is it necessary to wrap these static methods in a static class?
It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
In C#, any method has to be declared inside a class. That's just how the language is specified.
A static class is actually more akin to a module than a class, so I too think you should be able to either:
define a function outside a class or;
import a module the same way you import a namespace (with using)
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor are begging to be string extension methods.
This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)
It would be somewhat awkward to have methods just dangling around in a random namespace.
I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.
Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.
It's more of an organizational design than anything to due with technical limitations.
A static method is a method called in a single instance of a class that is created at run-time.
I found myself having to remove the first line of a string quite often while working on a text parser in C#. I put together a simple function to do that for me, but coming from a PHP background, I have no idea where to put it since I can't define a function outside a class. What's a customary way of doing that in .NET? Do I create a static class to store my function?
I generally make a Helper or Utility static class and then put corresponding helper functions in there.
Additionally, I try to keep the Helper and Utility classes grouped logically - putting the text parsing functions alongside the object conversion functions is nonsensical. The confusion is cleared up with a TextUtils class and a ConversionUtils class.
Yes, static helper classes are usually the way to do this.
Also, in C# 3 you can declare the method like this:
public static string RemoveFirstLine(this string s) {
...
}
to make it an extension method. Then you can call it on any string as if the method was declared on the string type itself.
Be careful!
Generic utility functions which are cross cutting should live in a higher utility namespace. String parsing, File manipulation, etc.
Extension objects should live in their own namespace.
Utility functions that apply to a specify set of business objects or methods should live within the namespace of those objects. Often with a Helper suffix, ie BusinessObjectHelper. Naming is important here. Are you creating a container for miscellaneous methods, or would it make more sense to group them into specialized objects, ie a parser?
I don't think there's a standard for this. I tend to make a static class called BlahUtil. For your example, I'd make it a static method on StringUtil. This helps me group related methods into sensible units, making it easier to discover them and share them across teams.
You can also then choose which of these methods are exposed as extension methods (since c# 3.0):
public static class StringUtil
{
public static string RemoveFirstLine(this string multiLineString)
{
// ...
}
}
If you are using C# 3.0, you might want to consider using an extension method!
public static class StringExtensions
{
public static string RemoveFirstLine(this string myString)
{
return myString.Remove("line..!");
}
}
Then in code you can do this:
string myString = "Hello World etc";
string removedLineString = myString.RemoveFirstLine();
Usually I create a Utilities class and define static helper methods.
I've done the static "helper" classes but after some analysis; this type of helper function always ends up as a distinct class implementation. In your case you'd have a "basic text parser" class and a derived class that overrides the "parse" method.
I'd create a static worker class for such functions. Maybe not the nicest way, but the one which keeps things simple... ;)
K
Use an extension method for a string. That's what they are for.
You can use a class with static methods. Something like ParserUtils.RemoveFirstLine(). On .NET 3.5 and above you can sometimes use extension methods when your utility functions are related to a class you cannot modify, like the String class. Intellisense will show the extension method on any string object in the project.
Extensions are the way to go in those case. It literally add your function to the occurence. Only thing is that it's not possible to do static method in 2008.