Methods inside namespace c# - c#

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)).

Related

Function 'class' in Unity/C#

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.

Is it possible to have Global Methods in C#

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

How to call an extension method without using

using System;
class Runner
{
static void Main()
{
A a = new A();
// how to say a.PrintStuff() without a 'using'
Console.Read();
}
}
class A { }
namespace ExtensionMethod
{
static class AExtensions
{
public static void PrintStuff(this A a)
{
Console.WriteLine("text");
}
}
}
How would I call the extension method without a 'using'? And not ExtensionMethod.AExtensions.PrintStuff(a), since that doesn't make use of extension method.
It is possible to directly call your extension like so since it is simply a static method, passing the instance it will act on as the first this parameter:
A a = new A();
ExtensionMethod.AExtensions.PrintStuff(a);
This might be confusing to other developers who happen across this code if you followed this pattern for more commonly used extension methods. It would also make chaining extension calls such as LINQ appear more like a functional language because you would be nesting each call instead of chaining them.
that is possible if Extension Method and class A in same namespace,
If you have to use different namespaces then you have to use using, i don't think there is a way to do this without using. But you may reduce the number of using by putting all the extensions in one namespace like for Linq (System.Linq.Extensions)
Note : You can remove the namespace for Extension methods, then it will make them globally available
It needs the using to know where the function lives.
One example of this in Linq. Without the System.Linq using - you won't have linq enabled for any of your IEnumerable<T>'s
However, you can define the extension method in the same namespace as the caller to avoid putting in a using. This approach will however not work if it's needed in many namespaces
This makes me feel dirty, but you can put your extension methods in the System namespace.
This namespace is included by default in your question
using System;
class Runner
{
static void Main()
{
A a = new A();
// how to say a.PrintStuff() without a 'using'
Console.Read();
}
}
class A { }
namespace System
{
static class AExtensions
{
public static void PrintStuff(this A a)
{
Console.WriteLine("text");
}
}
}
Ruminations on the creation of extension methods for a type ExtendableType:
Name the class ExtendableTypeExtensions
Declare the extension class partial so that clients can add extension methods following the same pattern; and
Put the extension methods in the same namespace as the base type
unless you have a very good reason to follow a model like that of LINQ:
A substantial family of extension methods,
That all apply to multiple base classes.
As of C# v6.0 (circa 2015) you can use using static to access a specific class's static members without including it's whole namespace.
An example, using your code, would be:
using System;
using static ExtensionMethod.AExtensions;
class Runner
{
static void Main()
{
A a = new A();
a.PrintStuff();
Console.Read();
}
}
class A { }
namespace ExtensionMethod
{
static class AExtensions
{
public static void PrintStuff(this A a)
{
Console.WriteLine("text");
}
}
}
You can add extensions method without namespace.
This will affect the whole systems which is not recommended.
public static class StringExtensions
{
public static void HelloWorld(this String s)
{
Console.Write("Hello World");
}
}
string str = "s";
str.HelloWorld();
In our projects extensions are placed in the same namespace as class extension for. Your example:
A.cs:
using System;
namespace ANamespace
{
class A { }
}
AExtensions.cs:
namespace ANamespace
{
static class AExtensions
{
public static void PrintStuff(this A a)
{
Console.WriteLine("text");
}
}
}
Now when you add using for ANamespace for using the A class, all extensions for A class will be included too.

C# Extension methods in static contexts and derived types

An existing type in C# need to be extended with some new methods, so that the following meets:
extension methods should resist in another assembly
they should appear like static methods of the original type
they should also be visible to implementors of derived classes of the original type
Example, Assembly Orig.dll:
public class Orig {
public static void Method1() { }
}
Assembly Extend.dll:
// method, which extends Orig in a static context is needed ...
// ??
// public static void Method2() { }
Usage Example (ideal):
public class Usage : Orig {
Method1(); // naturally working
Method2(); // <- this is needed
}
public void SomeFunc() {
Orig.Method2(); // <- this should ideally work also
}
The first attempt naturally coming in mind is using extension methods of C# 3.0. But unlike what I want, these (I think) only work on instances of the type being extended. In the context of a derived class this could be archieved like so:
public class Usage : Orig {
Method1(); // naturally working
this.Method2(); // working with C# 3.0 extension methods, but clumsy syntax
}
The first requirement (static context from outside the assembly) seems not to be fullfillable at all? So is there another potential approach?
#Edit: I may have not described the problem clearly. The needs are commented out in the following snippet (because they do not work with the common C# extension methods). So I try to find another approach, enabling the out-commented syntax:
// having a class
public class Orig { }
// which is extended with some functions (from another assembly)
public static class ExtOrig {
public static void ExtMeth (this Orig orig, string bla) {}
}
// derived classes should DIRECTLY!! see the extension
public class Derived : Orig {
public void MyMethod() {
// ExtMeth("inside orig"); <- does not work
this.ExtMeth("this derived"); // <- this keyword needed
}
// for static methods even worse:
public static void MyMethod2() {
// ExtMeth("inside orig"); <- does not work
// this.ExtMeth("this derived"); // <- 'this' not usable here :(
}
}
// for shorter syntax, static access would be needed
public class SomeClass {
private void SomeFunc() {
// Orig.ExtMeth("static orig"); <- does not work
new Orig().ExtMeth("outside orig"); // <- instance needed :(
// Derived.ExtMeth("static derived"); <- does not work
new Derived().ExtMeth("outside derived");
}
}
Extension methods can exist in a seperate assembly from the assembly containing the type you want to extend. The extending assembly simply needs to reference the original assembly. Any clients in other assemblies simply have to reference both the original assembly and the extending assembly.
Extension methods cannot appear as static methods on the type being extended. They can only appear as instance methods. There has been some discussion in the community about the need for static extension methods and possible implementations but, as far as I know, MS have not committed to adding this feature to C# as of yet.
Extension methods (with appropriate visibility) will be visible to both derived types, and any consumer of those derived types.
Extension methods or partial classes wont help you. Try using the Singleton design pattern as this may give you the behaviour you require using instance rather than static members

Is it possible to write a extension method for an abstract class

Why I'm unable to extend an abstract class. Is there any work around to achieve this?
In silverlight, Enum.GetNames is missing. So, I would like to extend it and have it in my utility assembly. By then, got into this.
The problem here is not that you can't add an extension method to an abstract class (you can - you can add an extension method to any type) - it's that you can't add a static method to a type with extension methods.
Extension methods are static methods that present themselves in C# as instance methods. But they're still static. Adding a static method to a type requires the ability to redefine the type, which you can only do if you have the source code :)
Best bet, if you want this method, is to write your own static and see if you can perhaps rip the code out of reflector.
However, it's entirely possible that it's not there because it's physically not supported in Silverlight (I don't know - I haven't investigate)
EDIT
Following on from your comment - and I hope that I've understood you here - I think what you want to be able to do is something like this (targetting object to prove the point):
public static class ExtraObjectStatics
{
public static void NewStaticMethod()
{
}
}
public class Test
{
public void foo()
{
//You can't do this - the static method doesn't reside in the type 'object'
object.NewStaticMethod();
//You can, of course, do this
ExtraObjectStatics.NewStaticMethod();
}
}
If you think about it - of course you can't inject new static methods into an existing type because, like I said in paragraph two, you have to be able to recompile the underlying type; and there simply is no way around that.
What you can do is (and I don't actually recommend this - but it's an option) create yourself a new type called Enum and place it inside a new namespace:
namespace MySystem
{
public class Enum
{
public static string[] GetNames()
{
//don't actually know how you're going to implement it :)
}
}
}
And now - when you want to use it, what you can't do is this:
using System;
using MySystem;
namespace MyCode
{
public class TestClass
{
public static void Test()
{
Enum.GetNames(); //error: ambiguous between System and MySystem
}
}
}
Because the using in the outermost scope to both 'System' and 'MySystem' will cause the compiler not to be able to resolve the correct Enum type.
What you can do, however, is this:
using System;
namespace MyCode
{
using MySystem; //move using to inside the namespace
public class TestClass
{
public static void Test()
{
//will now work, and will target the 'MySystem.Enum.GetNames()'
//method.
Enum.GetNames();
}
}
}
Now, code within that namespace (within that file only) will always resolve Enum to the one in your namespace because that's the nearest using directive in terms of scope.
So, you can think of this as overriding the whole Enum type for the benefit of a given namespace that includes a using MySystem; in it.
But, it does exactly that - it replaces the existing System.Enum with MySystem.Enum - meaning that you lose all the members of the System.Enum type.
You could get around this by writing wrapper methods in your Enum type around the System.Enum versions - making sure that you fully-qualify the type as System.Enum.
Having looked at the implementation of the GetNames method in Reflector - it relies on internal data that I don't think you're going to be able to build... but I would be very interested to hear if you are actually able to reproduce the method in Silverlight.
public abstract class Foo
{
public abstract void Bar();
}
public static class FooExtensions
{
// most useless extension method evar
public static void CallBar(this Foo me)
{
me.Bar();
}
}
Sure, no problem.

Categories